【发布时间】:2019-12-13 08:46:46
【问题描述】:
我尝试了一些可用的解决方案,但无法使用以下 Cython 代码获得任何加速。
cython 代码所用的时间与其对应的 python 代码相同。
calculate_sum.pyx
# key_id: it is a string
# values_dict: it is a dictionary with key as str and values as numpy.ndarray consisting of floats
# e.g.: print(values_dict['abc']) will give out numpy.ndarray([0.01, 1.01, 2.05]). values_dict has many such entries.
cpdef dict calculate_sum(str key_id, dict values_dict):
cdef dict result_dict = {}
cdef str check_id
for check_id, values in values_dict.items():
if check_id != key_id:
result_dict[check_id] = sum(values)
return result_dict
setup.py
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('calculate_sum.pyx'))
main.py
import calculate_sum
# ...
# piece of code which computes values_dict
# ...
key_id = 'abc'
sum_value = calculate_sum.calculate_sum(key_id, values_dict)
感谢任何建议/帮助。
【问题讨论】:
-
您是否对原始程序和 Cython 版本进行了任何基准测试/分析?
-
没有太多的基准。 python版本运行得更好,所以想知道是否有办法对其进行cythonize
-
忘了问:您这样做是为了教育目的,还是需要加快实际程序的速度?
-
这两个问题的答案都是:是的。需要加快代码速度,如果一切顺利,那么将编写一个关于 do's-n-dont's 的教程。
-
您的程序是否有很多地方都有数组循环,您一次只索引一个元素?如果“是”则 Cython 是正确的工具,如果“否”则 Cython 可能不是正确的工具。 (有时值得将 Numpy 数组操作展开到 Cython 中的循环中,但通常可以将多个操作组合在一起以避免临时操作)。互联网上有关于 Cython 的教程,然后主要处理 Numpy 和循环(因为这是它擅长的)