python - 为什么编译的 python 正则表达式更慢?

标签 python regex python-3.x

another SO question ,比较了正则表达式和 Python 的 in 运算符的性能。但是,接受的答案使用 re.match,它只匹配字符串的开头,因此与 in 的行为完全不同。另外,我想看看不每次都重新编译 RE 的性能提升。

令人惊讶的是,我看到预编译版本似乎

有什么想法吗?

我知道这里还有很多其他问题想知道类似的问题。他们中的大多数执行他们的方式只是因为他们没有正确地重用编译的正则表达式。如果这也是我的问题,请解释。

from timeit import timeit
import re

pattern = 'sed'
text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod' \
       'tempor incididunt ut labore et dolore magna aliqua.'

compiled_pattern = re.compile(pattern)

def find():
    assert text.find(pattern) > -1

def re_search():
    assert re.search(pattern, text)

def re_compiled():
    assert re.search(compiled_pattern, text)

def in_find():
    assert pattern in text

print('str.find     ', timeit(find))
print('re.search    ', timeit(re_search))
print('re (compiled)', timeit(re_compiled))
print('in           ', timeit(in_find))

输出:

str.find      0.36285957560356435
re.search     1.047689160564772
re (compiled) 1.575113873320307
in            0.1907925627077569

最佳答案

简答

如果您调用 compiled_pattern.search(text)直接,它根本不会调用 _compile,它会比 re.search(pattern, text) 快并且比 re.search(compiled_pa​​ttern, text) 快得多。

这种性能差异是由于缓存中的 KeyError 和编译模式的缓慢哈希计算造成的。


re 函数和 SRE_Pattern 方法

任何时候以 pattern 作为第一个参数的 re 函数(例如 re.search(pattern, string)re .findall(pattern, string)) 被调用时,Python 尝试先用_compile 编译pattern,然后在已编译的模式上调用相应的方法。对于 example :

def search(pattern, string, flags=0):
    """Scan through string looking for a match to the pattern, returning
    a match object, or None if no match was found."""
    return _compile(pattern, flags).search(string)

请注意,pattern 可以是字符串或已编译的模式(SRE_Pattern 实例)。

_编译

这是 _compile 的精简版.我只是删除了调试和标志检查:

_cache = {}
_pattern_type = type(sre_compile.compile("", 0))
_MAXCACHE = 512

def _compile(pattern, flags):
    try:
        p, loc = _cache[type(pattern), pattern, flags]
        if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE):
            return p
    except KeyError:
        pass
    if isinstance(pattern, _pattern_type):
        return pattern
    if not sre_compile.isstring(pattern):
        raise TypeError("first argument must be string or compiled pattern")
    p = sre_compile.compile(pattern, flags)
    if len(_cache) >= _MAXCACHE:
        _cache.clear()
    loc = None
    _cache[type(pattern), pattern, flags] = p, loc
    return p

_compile 字符串模式

当使用字符串模式调用_compile时,编译后的模式保存在_cache字典中。下次调用相同的函数时(例如,在许多 timeit 运行期间),_compile 只需检查 _cache 是否已经看到该字符串,并且返回相应的编译模式。

在 Spyder 中使用 ipdb 调试器,很容易在执行过程中深入 re.py

import re

pattern = 'sed'
text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod' \
       'tempor incididunt ut labore et dolore magna aliqua.'

compiled_pattern = re.compile(pattern)

re.search(pattern, text)
re.search(pattern, text)

在第二个re.search(pattern, text)处设置断点,可以看出:

{(<class 'str'>, 'sed', 0): (re.compile('sed'), None)}

保存在_cache中。编译后的模式直接返回。

_compile 编译模式

慢散列

如果使用已编译的模式调用 _compile 会发生什么情况?

首先,_compile 检查模式是否在_cache 中。为此,它需要计算其哈希值。编译模式的计算比字符串慢得多:

In [1]: import re

In [2]: pattern = "(?:a(?:b(?:b\\é|sorbed)|ccessing|gar|l(?:armists|ternation)|ngels|pparelled|u(?:daciousness's|gust|t(?:horitarianism's|obiographi
   ...: es)))|b(?:aden|e(?:nevolently|velled)|lackheads|ooze(?:'s|s))|c(?:a(?:esura|sts)|entenarians|h(?:eeriness's|lorination)|laudius|o(?:n(?:form
   ...: ist|vertor)|uriers)|reeks)|d(?:aze's|er(?:elicts|matologists)|i(?:nette|s(?:ciplinary|dain's))|u(?:chess's|shanbe))|e(?:lectrifying|x(?:ampl
   ...: ing|perts))|farmhands|g(?:r(?:eased|over)|uyed)|h(?:eft|oneycomb|u(?:g's|skies))|i(?:mperturbably|nterpreting)|j(?:a(?:guars|nitors)|odhpurs
   ...: 's)|kindnesses|m(?:itterrand's|onopoly's|umbled)|n(?:aivet\\é's|udity's)|p(?:a(?:n(?:els|icky|tomimed)|tios)|erpetuating|ointer|resentation|
   ...: yrite)|r(?:agtime|e(?:gret|stless))|s(?:aturated|c(?:apulae|urvy's|ylla's)|inne(?:rs|d)|m(?:irch's|udge's)|o(?:lecism's|utheast)|p(?:inals|o
   ...: onerism's)|tevedore|ung|weetest)|t(?:ailpipe's|easpoon|h(?:ermionic|ighbone)|i(?:biae|entsin)|osca's)|u(?:n(?:accented|earned)|pstaging)|v(?
   ...: :alerie's|onda)|w(?:hirl|ildfowl's|olfram)|zimmerman's)"

In [3]: compiled_pattern = re.compile(pattern)

In [4]: % timeit hash(pattern)
126 ns ± 0.358 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [5]: % timeit hash(compiled_pattern)
7.67 µs ± 21 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

hash(compiled_pa​​ttern) 比此处的 hash(pattern) 慢 60 倍。

按键错误

pattern 未知时,_cache[type(pattern), pattern, flags] 失败并返回 KeyError

KeyError 被处理并被忽略。只有这样,_compile 才会检查模式是否已经编译。如果是,它会被返回,而不写入缓存。

这意味着下次使用相同的编译模式调用 _compile 时,它会再次计算无用的、缓慢的哈希,但仍然会失败并返回 KeyError

错误处理代价高昂,我想这就是 re.search(compiled_pa​​ttern, text)re.search(pattern, text) 慢的主要原因。

这种奇怪的行为可能是加速字符串模式调用的一种选择,但如果使用已编译的模式调用 _compile,写一个警告可能是个好主意。

关于python - 为什么编译的 python 正则表达式更慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477347/

相关文章:

python - 复制文件,保留权限和所有者

javascript - PHP基于正则表达式显示弹出消息

javascript - Python Flask将变量传递给html文件在脚本标签下不起作用

python - 将 functools.partial 与部分参数一起使用

python-3.x - 如何根据 Keras 中的输出概率区分其为 True 或 False?

python - 简单 python 日志记录配置中的重复输出

python - 将属性修饰的成员复制到新类

python - 并行化使用 rpy2 的 python 代码的最有效方法是什么?

python正则表达式在标点符号和字母之间插入一个空格

python - 将 pandas 提取正则表达式与多个组一起使用