python - 如果更改 python 中编译和查找的顺序,为什么性能会有所不同

标签 python regex compilation findall

我注意到通过编译模式进行预处理会加快匹配操作,就像下面的例子一样。

python3 -m timeit -s "import re; t = re.compile(r'[\w+][\d]+')" "t.findall('abc eft123&aaa123')"

1000000 次循环,3 次最佳:每次循环 1.42 usec

python3 -m timeit -s "import re;" "re.findall(r'[\w+][\d]+', 'abc eft123&aaa123')"

100000 次循环,3 次最佳:每次循环 2.45 usec

但是如果我改变编译模式和re module的顺序,结果不一样,现在好像慢了很多,为什么会这样?

python3 -m timeit -s "import re; t = re.compile(r'[\w+][\d]+')" "re.findall(t, 'abc eft123&aaa123')"

100000 次循环,3 次最佳:每次循环 3.66 usec

最佳答案

通过“改变顺序”,您实际上是在以“静态”形式使用 findall,这几乎等同于调用 str.lower('ABC') 'ABC'.lower() 的。

根据您使用的 Python 解释器的具体实现,这可能会导致一些开销(例如方法查找)。

换句话说,这更多地与 Python 的工作方式有关,而不是专门针对正则表达式或 re 模块。

from timeit import Timer

def a():
    str.lower('ABC')

def b():
    'ABC'.lower()

print(min(Timer(a).repeat(5000, 5000)))
print(min(Timer(b).repeat(5000, 5000)))

输出

0.001060427000000086    # str.lower('ABC')
0.0008686820000001205   # 'ABC'.lower()

关于python - 如果更改 python 中编译和查找的顺序,为什么性能会有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53257939/

相关文章:

python - 带有Dropbox API的AWS Chalice

python 基维 : unable to import main main

regex - 连续 3 个不同元音的正则表达式

python - 使用时间索引时 pandas 中的 xtick 标签格式

python - 无法启动 Django 应用程序

Java URL 正则表达式不匹配

python - 如何检查一个字符串是否在2个字符串之间,并用正则表达式返回以下字符

c - Arduino 代码保存后无法编译

c++ - 如何配置 autoreconf 使用不同于 GCC 的编译器

c++ - 在 C++ 的编译期间成员函数是否可用?