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

Measuring Time

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

In [1]:
import fuzzingbook_utils
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.04350709200025449
In [7]:
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())
Stopping time in between:
3.072999788855668e-06
6.375699922500644e-05
0.00032886200006032595
0.0003797529998337268
0.0003976899997724104
0.00041616799990151776
0.0004380209993541939
0.00045481599954655394
0.00046889599980204366
0.00048251899988827063

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