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 debuggingbook.Timer import <identifier>

and then make use of the following features.

Note: The examples in this section only work after the rest of the cells have been executed.

In [10]:
with Timer() as t:
    some_long_running_function()
t.elapsed_time()
Out[10]:
0.030439833004493266

Measuring Time¶

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

In [3]:
# ignore
from typing import Type, Any
In [4]:
def clock() -> float:
    """
    Return the number of fractional seconds elapsed since some point of reference.
    """
    return time.perf_counter()
In [6]:
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:

In [7]:
def some_long_running_function() -> None:
    i = 1000000
    while i > 0:
        i -= 1
In [8]:
print("Stopping total time:")
with Timer() as t:
    some_long_running_function()
print(t.elapsed_time())
Stopping total time:
0.03074662500876002
In [9]:
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.030248791998019442
0.060225916997296736
0.09011208399897441
0.12019625000539236
0.1499536250194069
0.17993966699577868
0.21137279199319892
0.24325558400596492
0.2745761669939384
0.30587045900756493

That's it, folks – enjoy!

Lessons Learned¶

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