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())
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.04285796100157313
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.6349880499765277e-06
3.095399006269872e-05
4.091499431524426e-05
5.3956988267600536e-05
0.0002664629864739254
0.0003143059875583276
0.0007870579865993932
0.0008113869989756495
0.0008266049990197644
0.0008405959961237386

That's it, folks – enjoy!