Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # timeit_dot_operator.py
- import timeit
- '''
- Don't Access Attributes
- Another thing that might slow down your programs is dot operator (.) which is used when accessing object attributes. This operator triggers dictionary lookup using __getattribute__, which creates extra overhead in your code. So, how can we actually avoid (limit) using it?
- '''
- regex = '"(.*?)"'
- line = '''outside double quotes "1: in" abc: out ,"2: in" xyz: out'''
- import re
- def slow_func():
- return re.findall(regex, line) # Slow!
- from re import findall
- def fast_func():
- return findall(regex, line) # Fast!
- def repl_func():
- return line.split('"')[1::2]
- print slow_func()
- print fast_func()
- print repl_func()
- print
- iterations = 100000
- fn = 'slow_func','fast_func','repl_func'
- t = {}
- for z in [0,1,2]:
- repeat = []
- for n in xrange(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 'Method #{} {} took {} seconds : best out of {}'.format(z+1,fn[z],t,len(repeat))
- print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement