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

Measuring Time

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

In [1]:
import bookutils
In [2]:
import time
In [3]:
def clock():
    try:
        return time.perf_counter()  # Python 3
    except:
        return time.clock()         # Python 2
In [4]:
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:

In [5]:
def some_long_running_function():
    i = 1000000
    while i > 0:
        i -= 1
In [6]:
print("Stopping total time:")
with Timer() as t:
    some_long_running_function()
print(t.elapsed_time())
Stopping total time:
0.045178532999671006
In [7]:
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())
Stopping time in between:
2.618000053189462e-06
2.4245000076916767e-05
3.2579000162513694e-05
4.00960002480133e-05
4.6999999995023245e-05
6.355000004987232e-05
7.370399998762878e-05
8.365300027435296e-05
9.213900011673104e-05
0.00010193300022365293

That's it, folks – enjoy!

Synopsis

The Timer class allows you to measure elapsed real time. Its typical usage is in conjunction with a with clause:

In [8]:
with Timer() as t:
    some_long_running_function()
t.elapsed_time()
Out[8]:
0.04306673300015973

Lessons Learned

  • With the Timer class, it is very easy to measure elapsed time.