Python面试:使用Cython提升代码运行速度

1. 首先建立一个pyx文档。

main.pyx

# 以下函数用于找出所有小于amount的质数
# python版本
def prime_finder_python(amount):
    primes = []

    found = 0
    number = 2
    while found < amount:
        for x in primes:
            if number % x == 0:
                break
        else:
            primes.append(number)
            found += 1
        number += 1
    return primes

# c版本
def prime_finder_optimized(int amount):
    cdef int number, x, found 
    cdef int primes[100000]

    amount = min(amount, 100000)

    found = 0
    number = 2
    while found < amount:
        for x in primes[:found]:
            if number % x == 0:
                break
        else:
            primes[found] = number
            found += 1

        number += 1

    return_list = [p for p in primes[:found]]
    return return_list

2. 接着建立一个setup

setup.py

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize('main.pyx')
)

3. 在CMD中执行指令“python setup.py build_ext --inplace”

建立相应的c文档
成功后会生成两个文档“main.cp310-win_amd64.pyd”和“main.c”

4. 建立一个执行文档

test.py

import main
import time

print(main.prime_finder_python(40))

5. 测试时间

import main
import time

start_python = time.time()
main.prime_finder_python(20000)
end_python = time.time()

print(end_python - start_python)

start_c = time.time()
main.prime_finder_optimized(20000)
end_c = time.time()

print(end_c - start_c)

输出为:
3.2258031368255615
0.40691256523132324

我们可以看到,对于同一个函数,C版本的执行时间为Python版本的1/8,大大提升了代码运行速度。

你可能感兴趣的:(Python,python,开发语言)