vegaseat

timeit of a simple Python statement

Mar 13th, 2015
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. ''' timeit_lambda_simple101.py
  2. using Python module timeit on a simple statement
  3. (by default timeit turns off garbage collection)
  4.  
  5. if you have iPython running it is even simpler ...
  6. In [1]: %timeit not 9999991 & 1
  7. 10000000 loops, best of 3: 39.9 ns per loop
  8.  
  9. In [2]: %timeit 9999991 % 2 == 0
  10. 10000000 loops, best of 3: 60 ns per loop
  11. '''
  12.  
  13. import timeit
  14.  
  15. '''
  16. # use n=1000000 passes (this is also the default)
  17. # this way the result will be time per pass in microseconds
  18. elapsed = lambda stmt, n=1000000: timeit.Timer(stmt).timeit(n)
  19. '''
  20.  
  21. # or even simpler
  22. # using default 1000000 passes --> micro-seconds/pass
  23. elapsed = lambda stmt: timeit.Timer(stmt).timeit()
  24.  
  25. stmt = "x = (12345679 * 63)//7"
  26. # run and show the timeit test
  27. print("'%s' took %0.3f micro-seconds" % (stmt, elapsed(stmt)))
  28.  
  29. stmt = "not 9999991 & 1"  # True if even
  30. # run and show the timeit test
  31. print("'%s' took %0.3f micro-seconds" % (stmt, elapsed(stmt)))
  32.  
  33. stmt = "9999991 % 2 == 0"   # True if even
  34. # run and show the timeit test
  35. print("'%s' took %0.3f micro-seconds" % (stmt, elapsed(stmt)))
  36.  
  37. ''' result (Python 3.4.1 64bit) -->
  38. 'x = (12345679 * 63)//7' took 0.022 micro-seconds
  39. 'not 9999991 & 1' took 0.033 micro-seconds
  40. '9999991 % 2 == 0' took 0.054 micro-seconds
  41. '''
Advertisement
Add Comment
Please, Sign In to add comment