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

Measuring Time

The class Timer allows to measure the elapsed time during some code execution. A typical usage looks as follows:

from Timer import Timer

with Timer() as t:
    function_that_is_supposed_to_be_timed()

print(t.elapsed_time())
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.042989182999008335
print("Stopping time in between:")
with Timer() as t:
    for i in range(10):
        print(t.elapsed_time())
Stopping time in between:
2.3940010578371584e-06
2.707199746510014e-05
3.557199670467526e-05
4.228400212014094e-05
8.418499783147126e-05
0.0001215859956573695
0.00016172300092875957
0.0001878219991340302
0.0001953570026671514
0.0003257189964642748

That's it, folks – enjoy!

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: 2019-01-03 16:04:11+01:00CiteImprint