使用cython库对python代码进行动态编译达到加速效果及python第三方包的制作安装

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())

5、可以通过:

  python fib_setup.py install 

为python安装此包到全局路径中进行使用

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

 

 

 



posted @ 2019-07-07 00:20  洺剑残虹  阅读(989)  评论(0编辑  收藏  举报