I\'m programming in python on windows and would like to accurately measure the time it takes for a function to run. I have written a function \"time_it\" that takes another
If you want to time a python method even if block you measure may throw, one good approach is to use with
statement. Define some Timer
class as
import time
class Timer:
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, *args):
self.end = time.clock()
self.interval = self.end - self.start
Then you may want to time a connection method that may throw. Use
import httplib
with Timer() as t:
conn = httplib.HTTPConnection('google.com')
conn.request('GET', '/')
print('Request took %.03f sec.' % t.interval)
__exit()__
method will be called even if the connection request thows. More precisely, you'd have you use try
finally
to see the result in case it throws, as with
try:
with Timer() as t:
conn = httplib.HTTPConnection('google.com')
conn.request('GET', '/')
finally:
print('Request took %.03f sec.' % t.interval)
More details here.