Timer

The code in this notebook helps with measuring time.

Prerequisites

  • This notebook needs some understanding on advanced concepts in Python, notably
    • classes
    • the Python with statement
    • measuring time

Synopsis

To 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. Its typical usage is in conjunction with a with clause:

>>> with Timer() as t:
>>>     some_long_running_function()
>>> t.elapsed_time()
0.4898100739810616

Measuring Time

The class Timer allows to measure the elapsed time during some code execution.

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.44787194300442934
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())
Stopping time in between:
4.3879845179617405e-06
4.889100091531873e-05
7.351196836680174e-05
9.593699360266328e-05
0.00011839298531413078
0.000139854964800179
0.00016060296911746264
0.00018131796969100833
0.0003420559805817902
0.0003757869708351791

That's it, folks – enjoy!

>