如何优化这个cython代码?我发现速度只提高了 3%
How to optimize this cython code? I found only 3 percent increase in speed
这是我的 fun.pyx 文件
cimport cython
@cython.boundscheck(False)
cdef long long int extr():
cdef long long int i=0;
while i<=20000000000:
i=i+1
return i
def fn():
return extr()
这是我的 test.py 文件
from fun import fn
import time
t1=time.time()
print(fn())
print(time.time()-t1)
但是经过运行这个,我发现比python速度只提高了3% program.How优化这个程序?
任何建议都会有所帮助。
提前致谢。
我运行以下基准测试并找到了合适的加速
cimport cython
from cython.operator cimport preincrement as inc
@cython.boundscheck(False)
cpdef long long int extr():
cdef long long int i=0;
while i<=200000:
inc(i)
return i
Python 函数
def pextr():
i=0;
while i<=200000:
i +=1
return i
现在进行基准测试:
%timeit extr()
The slowest run took 16.55 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 67.2 ns per loop
%timeit pextr()
100 loops, best of 3: 15.6 ms per loop
In [3]:
你构建正确吗?您将需要使用 pyximport 或拥有适当的 setup.py 脚本
我还注意到您正在使用 fn 来执行此代码,您可能已经意识到无法将 cdef 导入 python 文件。但是,如果你只是将你的函数保存为cpdef,你可以直接使用它
这是我的 fun.pyx 文件
cimport cython
@cython.boundscheck(False)
cdef long long int extr():
cdef long long int i=0;
while i<=20000000000:
i=i+1
return i
def fn():
return extr()
这是我的 test.py 文件
from fun import fn
import time
t1=time.time()
print(fn())
print(time.time()-t1)
但是经过运行这个,我发现比python速度只提高了3% program.How优化这个程序? 任何建议都会有所帮助。 提前致谢。
我运行以下基准测试并找到了合适的加速
cimport cython
from cython.operator cimport preincrement as inc
@cython.boundscheck(False)
cpdef long long int extr():
cdef long long int i=0;
while i<=200000:
inc(i)
return i
Python 函数
def pextr():
i=0;
while i<=200000:
i +=1
return i
现在进行基准测试:
%timeit extr()
The slowest run took 16.55 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 67.2 ns per loop
%timeit pextr()
100 loops, best of 3: 15.6 ms per loop
In [3]:
你构建正确吗?您将需要使用 pyximport 或拥有适当的 setup.py 脚本
我还注意到您正在使用 fn 来执行此代码,您可能已经意识到无法将 cdef 导入 python 文件。但是,如果你只是将你的函数保存为cpdef,你可以直接使用它