RegEx-Performance Beispiele
Verfasst: Freitag 23. Februar 2007, 00:03
Hallo,
die Grundidee ist aus der englischen Gruppe.
Interressant ist vor allem, dass ein unglücklicher RegEx sehr langsam werden kann.
Sind die Vergleiche für Euch gültig?
Gruß P.
die Grundidee ist aus der englischen Gruppe.
Code: Alles auswählen
#
import timeit
import re
loop = 1000000
line = """
a sample line that will not match any condition, but long enough to
be meaninful in the context of this problem, or at least I thik so. This has 174
characters, is it enough?
"""
error_l1 = re.compile(r'error|miss|issing|inval|nvalid|math')
error_l2 = re.compile(r'error|m?(iss(?:ing)?|ath)|i?nval(?:id)?')
tokens = "error|miss|issing|inval|nvalid|math".split("|")
s1 = """#
from __main__ import line, error_l1
if error_l1.search(line): pass
"""
t1 = timeit.Timer(stmt = s1)
print "%.2f usec/pass" % (loop * t1.timeit(number = loop) / loop)
s2 = """#
from __main__ import line, tokens
for token in tokens:
if token in line: break
"""
t2 = timeit.Timer(stmt = s2)
print "%.2f usec/pass" % (loop * t2.timeit(number = loop) / loop)
s3 = """#
from __main__ import line
if "error" in line or "miss" in line or "issing" in line or "inval" in line or "nvalid" in line or "math" in line: pass
"""
t3 = timeit.Timer(stmt = s3)
print "%.2f usec/pass" % (loop * t3.timeit(number = loop) / loop)
s4 = """#
from __main__ import line, error_l2
if error_l2.search(line): pass
"""
t4 = timeit.Timer(stmt = s4)
print "%.2f usec/pass" % (loop * t4.timeit(number = loop) / loop)
Sind die Vergleiche für Euch gültig?
Code: Alles auswählen
t1 -- 29.95 usec/pass
te -- 39.47 usec/pass
t3 -- 37.33 usec/pass
t4 -- 85.57 usec/pass