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
setup.py
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize('main.pyx')
)
建立相应的c文档
成功后会生成两个文档“main.cp310-win_amd64.pyd”和“main.c”
test.py
import main
import time
print(main.prime_finder_python(40))
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