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())
import fuzzingbook_utils
import 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.06727509300071688
print("Stopping time in between:")
with Timer() as t:
for i in range(10):
print(t.elapsed_time())
Stopping time in between: 4.9720001698005944e-06 5.465600042953156e-05 8.613899990450591e-05 0.00011476500003482215 0.00014296199879026972 0.00017072300033760257 0.00042000499888672493 0.00047452599937969353 0.0005045199995947769 0.0005325679994712118
That's it, folks – enjoy!