我曾经通过在扩展源代码的顶级目录下从“Visual Studio 2008 x64 Win64命令提示符”运行以下命令,成功地为Python编译了C扩展:
set DISTUTILS_USE_SDK=1
set MSSdk=1
python setup.py install
c_prime.pyx:
def calculate(long limit):
cdef long current
cdef long divisor
primes = []
divisor = 0
for current in range(limit):
previous = []
for divisor in range(2, current):
if current % divisor == 0:
break
if divisor == current - 1:
primes.append(current)
return primes
setup.py:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(
name = 'PrimeTest',
ext_modules=[
Extension('c_prime', ['c_prime.pyx'])
],
cmdclass = {'build_ext': build_ext}
)
编译:
python setup.py build_ext --inplace --compiler=msvc
test_prime.py:
from timeit import Timer
t = Timer('c_prime.calculate(10000)', 'import c_prime')
reps = 5
print(sum(t.repeat(repeat=reps, number=1)) / reps)