1、测试代码:新建 fib.pyx
# coding:utf-8 import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans def 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 setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( 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 --inplace import myfib import time t = time.time() myfib.fib(37) print(time.time() - t) print(myfib.km())
测试成功搞定,这种方法可以提高python一大截计算速度。还可以吧
原文地址:https://www.cnblogs.com/wuzaipei/p/11144827.html
时间: 2024-10-07 11:44:59