Skip to main content
 首页 » 编程设计

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

2024年12月31日9jiqing9006

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

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()