Advertisement
here2share

# timeit_dot_operator.py

Jan 21st, 2020
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. # timeit_dot_operator.py
  2.  
  3. import timeit
  4.  
  5. '''
  6. Don't Access Attributes
  7.  
  8. 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?
  9. '''
  10.  
  11. regex = '"(.*?)"'
  12. line = '''outside double quotes "1: in" abc: out ,"2: in" xyz: out'''
  13.  
  14. import re
  15. def slow_func():
  16.     return re.findall(regex, line)  # Slow!
  17.  
  18. from re import findall
  19. def fast_func():
  20.     return findall(regex, line)  # Fast!
  21.  
  22. def repl_func():
  23.     return line.split('"')[1::2]
  24.  
  25. print slow_func()
  26. print fast_func()
  27. print repl_func()
  28. print
  29.  
  30. iterations = 100000
  31. fn = 'slow_func','fast_func','repl_func'
  32. t = {}
  33. for z in [0,1,2]:
  34.     repeat = []
  35.     for n in xrange(5):
  36.         t = 'from __main__ import %s; %s()'%(fn[z],fn[z])
  37.         ttt = timeit.Timer(t)
  38.         t = ttt.timeit(iterations)
  39.         repeat += [t]
  40.     t = min(repeat)
  41.     print 'Method #{} {} took {} seconds : best out of {}'.format(z+1,fn[z],t,len(repeat))
  42.     print
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement