使用cython库对python代码进行动态编译达到加速效果,,1、测试代码:新建


1、测试代码:新建 fib.pyx

# coding:utf-8import matplotlib.pyplot as pltimport numpy as npfrom sklearn.cluster import KMeansdef km():    return KMeans(n_clusters=4)def fib(n):    if n<2:        return 1    else:        return fib(n-1)+fib(n-2)def plots():    x  = np.linspace(-2,2,30)    y = np.sin(x)    plt.plot(x,y)    plt.show()

2、新建 fib_setup.py

from distutils.core import setupfrom distutils.extension import Extensionfrom Cython.Distutils import build_extsetup(    cmdclass={‘build_ext‘: build_ext},    ext_modules=[Extension("myfib", ["fib.pyx"])])

3、在当前文件下打开cmd执行:

python fib_setup.py build_ext --inplace

4、新建 test.py

# coding=utf-8# 把python代码编译成动态文件# python fib_setup.py build_ext --inplaceimport myfibimport timet = time.time()myfib.fib(37)print(time.time() - t)print(myfib.km())

测试成功搞定,这种方法可以提高python一大截计算速度。还可以吧



使用cython库对python代码进行动态编译达到加速效果

评论关闭