Advertisement
here2share

# timeit_regex_vs_replace.py

Jan 21st, 2020
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. # timeit_regex_vs_replace.py
  2.  
  3. import re
  4. import timeit
  5.  
  6. # Method #1 (string ops)
  7. sss = "hello@abc123xyz = test sample"
  8. def stringOps():
  9.     s=sss
  10.     replaceChar = s.split('@')[1].split(' ')[0]
  11.     s = s.split('=')[0].replace(replaceChar, "world >>> ['{0}'] #1".format(replaceChar)).strip()
  12.     if not r: r.append([sss,s])
  13.  
  14. # Method #2 (regex)
  15. def regex():
  16.     s=sss
  17.     s = re.sub(r'(\w+)(\s*=.*\w+$)', r"world >>> ['\1'] #2", s)
  18.     if not r: r.append([sss,s])
  19.  
  20. iterations = 100000
  21. fn = 'stringOps','regex'
  22. t = {}
  23. for z in [0,1]:
  24.     r = []
  25.     repeat = []
  26.     for n in range(5):
  27.         t = 'from __main__ import %s; %s()'%(fn[z],fn[z])
  28.         ttt = timeit.Timer(t)
  29.         t = ttt.timeit(iterations)
  30.         repeat += [t]
  31.     t = min(repeat)
  32.     print r[0][0]
  33.     print r[0][1]
  34.     print 'Method #{} took {} seconds : best out of {}'.format(z+1,t,len(repeat))
  35.     print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement