Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # timeit_regex_vs_replace.py
- import re
- import timeit
- # Method #1 (string ops)
- sss = "hello@abc123xyz = test sample"
- def stringOps():
- s=sss
- replaceChar = s.split('@')[1].split(' ')[0]
- s = s.split('=')[0].replace(replaceChar, "world >>> ['{0}'] #1".format(replaceChar)).strip()
- if not r: r.append([sss,s])
- # Method #2 (regex)
- def regex():
- s=sss
- s = re.sub(r'(\w+)(\s*=.*\w+$)', r"world >>> ['\1'] #2", s)
- if not r: r.append([sss,s])
- iterations = 100000
- fn = 'stringOps','regex'
- t = {}
- for z in [0,1]:
- r = []
- repeat = []
- for n in range(5):
- t = 'from __main__ import %s; %s()'%(fn[z],fn[z])
- ttt = timeit.Timer(t)
- t = ttt.timeit(iterations)
- repeat += [t]
- t = min(repeat)
- print r[0][0]
- print r[0][1]
- print 'Method #{} took {} seconds : best out of {}'.format(z+1,t,len(repeat))
- print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement