Python 无法使用cython获得预期的速度(在字符串列表中搜索)

Python 无法使用cython获得预期的速度(在字符串列表中搜索),python,cython,Python,Cython,我无法使用下面定义的函数bulk_phone_finder(使用phonenumbers pypi库)的cythonized版本加速计算,以: 我对cython有点陌生,但我设法制作了一个cython等效函数: # cython: c_string_type=unicode, c_string_encoding=utf8 from phonenumbers import PhoneNumberMatcher from phonenumbers.phonenumberutil import SUP

我无法使用下面定义的函数bulk_phone_finder(使用phonenumbers pypi库)的cythonized版本加速计算,以:

我对cython有点陌生,但我设法制作了一个cython等效函数:

# cython: c_string_type=unicode, c_string_encoding=utf8
from phonenumbers import PhoneNumberMatcher
from phonenumbers.phonenumberutil import SUPPORTED_REGIONS
from libcpp.vector cimport vector
from libcpp.string cimport string
from libcpp.set cimport set as c_set


cpdef c_set[string] _SUPPORTED_REGIONS = SUPPORTED_REGIONS

cdef get_phonenumbers(string content):
    res = set()
    cdef string cc
    cdef string raw_string
    for cc in _SUPPORTED_REGIONS :
        for m in PhoneNumberMatcher(content, cc):
            raw_string = m.raw_string
            res.add(raw_string)
    return res


def bulk_phone_finder(l):
    res=[]
    cpdef c_set[string] int_res
    cpdef string content
    for content in l :
        int_res= get_phonenumbers(content)
        res.append(int_res)
    return res

这个cython.pyx文件是用以下setup.py编译的

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup( ext_modules = cythonize(Extension(
            "bulk_phonenumber_finder",
            sources=["bulk_phonenumber_finder.pyx"],
            # extra_compile_args=["-std=c++11"],
            language="c++"
     )))
但我无法加快速度,因为:

lines=["0256985412"]*100

# cython version
In [6]: %timeit bulk_phonenumber_finder.bulk_phone_finder(lines)
9.39 s ± 363 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# python version
In [8]: %timeit bulk_phone_finder(lines)
9.44 s ± 213 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
你有什么建议来加速我的手机搜索功能吗

任何帮助都是非常受欢迎的


提前感谢,

每次使用C++数据类型时,Cython将不得不复制C++中的数据副本来填充它,然后必须再次复制它以将数据返回到Python。这些可能会使代码慢一些。这看起来不像是要加速太多的代码…你知道如何相应地修改我的代码以提高速度吗?我对cython有点陌生,谢谢againI,我看不到太多加快速度的机会。您是否尝试过使用Cython编译Python版本?我希望这能给我一个小小的提速。您分析过它吗(在未编译的Python版本上可能更容易完成)?我猜真正的工作都在你正在使用的库中,因此你在代码中所能做的很少。你需要
cdef
所有循环变量,但是如果你使用纯Python编写的库,你就无法达到Cython的目的,因为它必须从编译的C代码中调用Python代码。要么用Cython重写函数,要么尝试cythonize库^ ^'
lines=["0256985412"]*100

# cython version
In [6]: %timeit bulk_phonenumber_finder.bulk_phone_finder(lines)
9.39 s ± 363 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# python version
In [8]: %timeit bulk_phone_finder(lines)
9.44 s ± 213 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)