The code in this notebook helps with measuring time.
Prerequisites
with
statementThe class Timer
allows to measure the elapsed time during some code execution. A typical usage looks as follows:
from Timer import Timer
with Timer() as t:
function_that_is_supposed_to_be_timed()
print(t.elapsed_time())
def clock():
try:
return time.perf_counter() # Python 3
except:
return time.clock() # Python 2
class Timer(object):
# Begin of `with` block
def __enter__(self):
self.start_time = clock()
self.end_time = None
return self
# End of `with` block
def __exit__(self, exc_type, exc_value, tb):
self.end_time = clock()
def elapsed_time(self):
"""Return elapsed time in seconds"""
if self.end_time is None:
# still running
return clock() - self.start_time
else:
return self.end_time - self.start_time
Here's an example:
def some_long_running_function():
i = 1000000
while i > 0:
i -= 1
print("Stopping total time:")
with Timer() as t:
some_long_running_function()
print(t.elapsed_time())
Stopping total time: 0.040447834006045014
print("Stopping time in between:")
with Timer() as t:
for i in range(10):
print(t.elapsed_time())
Stopping time in between: 3.0320079531520605e-06 2.5946006644517183e-05 4.369599628262222e-05 6.079100421629846e-05 7.736199768260121e-05 9.499400039203465e-05 0.0001115360064432025 0.00012764200801029801 0.00014470599126070738 0.0001609699975233525
That's it, folks – enjoy!