【发布时间】:2020-09-16 17:29:45
【问题描述】:
我想比较一下 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
我该如何解决?如何在 .pyx 文件中正确定义 cpdef?
我错过了什么?
【问题讨论】:
-
Cythonizing fastfac.pyx,失败:
error: Unable to find vcvarsall.bat,你应该先解决这个问题 -
这能回答你的问题吗? error: Unable to find vcvarsall.bat
-
Duplicate 假设您安装了 Visual Studio。对你来说可能不是这样。然后你需要安装它。