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.04130863600585144

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.04219970799749717
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())
Stopping time in between:
2.6420020731166005e-06
2.31890007853508e-05
3.151000419165939e-05
3.8803002098575234e-05
4.568599979393184e-05
8.259800961241126e-05
0.00010635700891725719
0.0001350899983663112
0.00015377200907096267
0.00017481899703852832

That's it, folks – enjoy!

>