Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. def time_it(f, *args):
  2. start = time.clock()
  3. f(*args)
  4. return (time.clock() - start)*1000
  5.  
  6. from timeit import Timer
  7.  
  8. # first argument is the code to be run, the second "setup" argument is only run once,
  9. # and it not included in the execution time.
  10. t = Timer("""x.index(123)""", setup="""x = range(1000)""")
  11.  
  12. print t.timeit() # prints float, for example 5.8254
  13. # ..or..
  14. print t.timeit(1000) # repeat 1000 times instead of the default 1million
  15.  
  16. total= 0
  17. for i in range(1000):
  18. start= time.clock()
  19. function()
  20. end= time.clock()
  21. total += end-start
  22. time= total/1000
  23.  
  24. start= time.clock()
  25. for i in range(1000):
  26. function()
  27. end= time.clock()
  28. time= (end-start)/1000
  29.  
  30. import time
  31.  
  32. class Timer:
  33. def __enter__(self):
  34. self.start = time.clock()
  35. return self
  36.  
  37. def __exit__(self, *args):
  38. self.end = time.clock()
  39. self.interval = self.end - self.start
  40.  
  41. import httplib
  42.  
  43. with Timer() as t:
  44. conn = httplib.HTTPConnection('google.com')
  45. conn.request('GET', '/')
  46.  
  47. print('Request took %.03f sec.' % t.interval)
  48.  
  49. try:
  50. with Timer() as t:
  51. conn = httplib.HTTPConnection('google.com')
  52. conn.request('GET', '/')
  53. finally:
  54. print('Request took %.03f sec.' % t.interval)
  55.  
  56. from contextlib import contextmanager
  57.  
  58. import time
  59. @contextmanager
  60. def timeblock(label):
  61. start = time.clock()
  62. try:
  63. yield
  64. finally:
  65. end = time.clock()
  66. print ('{} : {}'.format(label, end - start))
  67.  
  68.  
  69.  
  70. with timeblock("just a test"):
  71. print "yippee"
  72.  
  73. import timeit
  74. timeit.timeit(fun, number=10000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement