import timeit
import __main__
import random
import string
import re
N = 10 #Number of executions
L = 1000000 #Length of string
sym_rel_pos = 2
def test_f_re():
pat = ''.join(random.sample(string.ascii_letters,3)) #prevent re caching
s = '0'*(L - sym_rel_pos) + pat + '0'*sym_rel_pos
return re.sub(r'(.*)'+pat,r'\1XXX',s)
compiled = re.compile(r'(.*)'+'jjj')
def test_f_re_with_caching():
pat = ''.join(random.sample(string.ascii_letters,3)) #left here to produce comparable results with other functions
s = '0'*(L - sym_rel_pos) + 'jjj' + '0'*sym_rel_pos
return compiled.sub(r'\1XXX',s)
def test_f_replace():
pat = ''.join(random.sample(string.ascii_letters,3))
s = '0'*(L - sym_rel_pos) + pat + '0'*sym_rel_pos
return s[::-1].replace(pat[::-1], "XXX"[::-1], 1)[::-1]
names = dir(__main__)
for name in names:
attr = getattr(__main__,name)
if hasattr(attr,'__call__'):
if name.startswith('test_f_'):
init_name = name + '_init'
if hasattr(__main__, init_name):
init = getattr(__main__,init_name)
else:
init = 'from __main__ import {name}'.format(name=name, L=L)
t = timeit.Timer(stmt='{name}()'.format(name=name),
setup=init)
time = t.timeit(N)
print('{name}: {time}'.format(name=name,time=time))
aW1wb3J0IHRpbWVpdAppbXBvcnQgX19tYWluX18KaW1wb3J0IHJhbmRvbQppbXBvcnQgc3RyaW5nCmltcG9ydCByZQoKTiA9IDEwICNOdW1iZXIgb2YgZXhlY3V0aW9ucwpMID0gMTAwMDAwMCAjTGVuZ3RoIG9mIHN0cmluZwpzeW1fcmVsX3BvcyA9IDIKCmRlZiB0ZXN0X2ZfcmUoKToKICAgIHBhdCA9ICcnLmpvaW4ocmFuZG9tLnNhbXBsZShzdHJpbmcuYXNjaWlfbGV0dGVycywzKSkgI3ByZXZlbnQgcmUgY2FjaGluZwogICAgcyA9ICcwJyooTCAtIHN5bV9yZWxfcG9zKSArIHBhdCArICcwJypzeW1fcmVsX3BvcwogICAgcmV0dXJuIHJlLnN1YihyJyguKiknK3BhdCxyJ1wxWFhYJyxzKQoKY29tcG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