我想把Python和Cython在时间执行方面进行比较,所以我写了两个文件。
fac.py
def factorial(n):
if n >= 1:
return n*factorial(n - 1)
return 1
fastfac.pyx
cpdef long fastfactorial(long n):
if n>= 1:
return n*fastfactorial(n - 1)
return 1
然后我写了一个设置文件。
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('fastfac.pyx'))
在Powershell中,我执行了两个命令。
pip install Cython
python setup.py build_ext --inplace
在第二条命令中,我得到了以下信息:
Compiling fastfac.pyx because it changed.
[1/1] Cythonizing fastfac.pyx
C:\Users\.....\venv\lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\Users\.....\fastfac.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
running build_ext
building 'fastfac' extension
error: Unable to find vcvarsall.bat
然而,我试图做一个比较,所以我写了一个文件:
comparison.py
from fastfac import fastfactorial
from fac import factorial
from timeit import timeit
print(timeit('fastfactorial(20)', globals = globals(), number = 10000))
print(timeit('factorial(20)', globals = globals(), number = 10000))
当我运行它时,我得到这个错误信息。
Traceback (most recent call last):
File "C:/Users/...../comparison.py", line 1, in <module>
from fastfac import fastfactorial
ModuleNotFoundError: No module named 'fastfac'
似乎在文件中 python.pyx
定义 cpdef long fastfactorial(long n)
并未被识别为常规函数定义,而是语法错误;事实上,如果我尝试运行该文件,会得到错误信息。
File "C:/Users/...../fastfac.pyx", line 1
cpdef long fastfactorial(long n):
^
SyntaxError: invalid syntax
我该如何解决?我如何才能正确定义一个 cpdef
在一个.pyx文件里面,我缺少什么?
问题不在于你对fastfactorial的定义,而在于你的setup.py在退出时出现了错误,而且可能没有将fastfac编译成c库。 一般来说,你应该总是修复这样的错误。
你的错误似乎是因为你没有安装Microsoft Visual C++编译器。 你可以按照 这个 答案来选择要安装的 Visual C++ 版本。
你也有一个关于 language_level 没有被设置的警告。 你也不应该忽略警告,所以值得在setup.py中明确说明级别。
setup(ext_modules=cythonize('fastfac.pyx'), language_level=3)