fork download
  1. import timeit
  2. import __main__
  3. import random
  4. import string
  5. import re
  6.  
  7. N = 10 #Number of executions
  8. L = 1000000 #Length of string
  9. sym_rel_pos = 2
  10.  
  11. def test_f_re():
  12. pat = ''.join(random.sample(string.ascii_letters,3)) #prevent re caching
  13. s = '0'*(L - sym_rel_pos) + pat + '0'*sym_rel_pos
  14. return re.sub(r'(.*)'+pat,r'\1XXX',s)
  15.  
  16. compiled = re.compile(r'(.*)'+'jjj')
  17. def test_f_re_with_caching():
  18. pat = ''.join(random.sample(string.ascii_letters,3)) #left here to produce comparable results with other functions
  19. s = '0'*(L - sym_rel_pos) + 'jjj' + '0'*sym_rel_pos
  20. return compiled.sub(r'\1XXX',s)
  21.  
  22. def test_f_replace():
  23. pat = ''.join(random.sample(string.ascii_letters,3))
  24. s = '0'*(L - sym_rel_pos) + pat + '0'*sym_rel_pos
  25. return s[::-1].replace(pat[::-1], "XXX"[::-1], 1)[::-1]
  26.  
  27. names = dir(__main__)
  28. for name in names:
  29. attr = getattr(__main__,name)
  30. if hasattr(attr,'__call__'):
  31. if name.startswith('test_f_'):
  32. init_name = name + '_init'
  33. if hasattr(__main__, init_name):
  34. init = getattr(__main__,init_name)
  35. else:
  36. init = 'from __main__ import {name}'.format(name=name, L=L)
  37. t = timeit.Timer(stmt='{name}()'.format(name=name),
  38. setup=init)
  39.  
  40. time = t.timeit(N)
  41. print('{name}: {time}'.format(name=name,time=time))
Success #stdin #stdout 0.24s 5600KB
stdin
Standard input is empty
stdout
test_f_re: 0.0586512088776
test_f_re_with_caching: 0.0592479705811
test_f_replace: 0.0910179615021