The code in this notebook helps with measuring time.
Prerequisites
with
statementTo use the code provided in this chapter, write
>>> from fuzzingbook.Timer import <identifier>
and then make use of the following features.
The Timer
class allows you to measure elapsed real time (in fractional seconds). Its typical usage is in conjunction with a with
clause:
>>> with Timer() as t:
>>> some_long_running_function()
>>> t.elapsed_time()
0.04699691599999989
The class Timer
allows to measure the elapsed time during some code execution.
import bookutils
import time
# ignore
from typing import Type, Any
def clock() -> float:
"""
Return the number of fractional seconds elapsed since some point of reference.
"""
return time.perf_counter()
from types import TracebackType
class Timer:
def __init__(self) -> None:
"""Constructor"""
self.start_time = clock()
self.end_time = None
def __enter__(self) -> Any:
"""Begin of `with` block"""
self.start_time = clock()
self.end_time = None
return self
def __exit__(self, exc_type: Type, exc_value: BaseException,
tb: TracebackType) -> None:
"""End of `with` block"""
self.end_time = clock() # type: ignore
def elapsed_time(self) -> float:
"""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 # type: ignore
Here's an example:
def some_long_running_function() -> None:
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.05019151199999983
print("Stopping time in between:")
with Timer() as t:
for i in range(10):
some_long_running_function()
print(t.elapsed_time())
Stopping time in between: 0.05081009000000014 0.09859830700000005 0.15091056700000016 0.199744492 0.251724984 0.30402183500000013 0.355143038 0.4076503680000001 0.45749869100000007 0.508016604
That's it, folks – enjoy!
The Timer
class allows you to measure elapsed real time (in fractional seconds). Its typical usage is in conjunction with a with
clause:
with Timer() as t:
some_long_running_function()
t.elapsed_time()
0.04699691599999989
Timer
class, it is very easy to measure elapsed time.