【使用cython编写的第三方库】

目的

  • 使用cython来封装你的第三方库,使其编译为c代码,有如下好处
    • 加速代码执行效率–>变异为c代码
    • 编译时,会优化代码的执行
    • 加密代码为so

安装cython

pip3 install cython

编写自定义代码库

  • ./cal/cal.pyx

from math import sqrt

def primes(n: int):
	"""
	primes(n: int=2) -> list
    求质数
    :param n: n
    :return: 返回列表
    """
    cdef int i, j
    results = [1, ]
    for i in range(2, n):
        for j in range(2, int(sqrt(i))):
            if i % j == 0:
                break
        else:
            results.append(i)
    return results
  • ./cal/init.py

from .cal import primes
  • 编写编译脚本setup.py

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(
    name='cal',
    version='1.0',
    ext_modules=cythonize(["./cal/*.pyx"]),
    package_data={'cal': ["*.so"]},
    packages=['cal', 'cal'],
)

编译库

[~]# python3 setup.py build_ext --inplace
running build_ext
building 'cal.cal' extension
gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/rockontrol/opt/miniconda3/include -arch x86_64 -I/Users/rockontrol/opt/miniconda3/include -arch x86_64 -I/Users/rockontrol/Desktop/python_code/venv/include -I/Users/rockontrol/opt/miniconda3/include/python3.8 -c ./cal/cal.c -o build/temp.macosx-10.9-x86_64-3.8/./cal/cal.o
gcc -bundle -undefined dynamic_lookup -L/Users/rockontrol/opt/miniconda3/lib -arch x86_64 -L/Users/rockontrol/opt/miniconda3/lib -arch x86_64 -arch x86_64 build/temp.macosx-10.9-x86_64-3.8/./cal/cal.o -o /Users/rockontrol/Desktop/python_code/code/test/c_test_module/cal/cal.cpython-38-darwin.so

测试test.py

import cal
import time
from math import sqrt

t1 = time.time()
cal.primes(3000000)
print(time.time() - t1)


def primes(n: int):
	"""原生python实现"""
    results = [1, ]
    for i in range(2, n):
        for j in range(2, int(sqrt(i))):
            if i % j == 0:
                break
        else:
            results.append(i)
    return results


t1 = time.time()
primes(3000000)
print(time.time() - t1)

测试结果

1.406919002532959
21.673776865005493
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值