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.

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

Measuring Time

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

import bookutils
import time
def clock() -> float:
    try:
        return time.perf_counter()  # Python 3
    except:
        return time.clock()         # Python 2
from types import FrameType, TracebackType
from typing import Type, Any
class Timer(object):
    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()

    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

Here's an example:

def some_long_running_function() -> None:
    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.04606053396128118
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())
Stopping time in between:
2.5259796530008316e-06
0.00018134398851543665
0.0002002469846047461
0.0002142610028386116
0.00022530497517436743
0.00023976899683475494
0.00024973799008876085
0.00026643997989594936
0.00028342800214886665
0.0002947170287370682

That's it, folks – enjoy!

Lessons Learned

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

Creative Commons License The content of this project is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. The source code that is part of the content, as well as the source code used to format and display that content is licensed under the MIT License. Last change: 2021-02-27 16:52:15+01:00CiteImprint