Skip to content

Timer

Timer

A simple class which can be used to time events.

Source code in ckantools/timer.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Timer:
    """
    A simple class which can be used to time events.
    """

    def __init__(self):
        """
        The timer is started upon instantiation (i.e. when this function is called).
        """
        self.start = datetime.now()
        self.events = []

    def add_event(self, label):
        """
        Add a new event at the current time with the given label.

        :param label: the label for the event
        """
        self.events.append((label, datetime.now()))

    def to_dict(self):
        """
        Return an OrderedDict of timings. Each key in the returned OrderedDict is a
        label and the value associated with it is the number of seconds it took between
        the previous event and this one.

        :return: an OrderedDict of events and how long they took
        """
        timings = OrderedDict()
        split = self.start
        for label, date in self.events:
            timings[label] = (date - split).total_seconds()
            split = date
        return timings

__init__()

The timer is started upon instantiation (i.e. when this function is called).

Source code in ckantools/timer.py
13
14
15
16
17
18
def __init__(self):
    """
    The timer is started upon instantiation (i.e. when this function is called).
    """
    self.start = datetime.now()
    self.events = []

add_event(label)

Add a new event at the current time with the given label.

Parameters:

Name Type Description Default
label

the label for the event

required
Source code in ckantools/timer.py
20
21
22
23
24
25
26
def add_event(self, label):
    """
    Add a new event at the current time with the given label.

    :param label: the label for the event
    """
    self.events.append((label, datetime.now()))

to_dict()

Return an OrderedDict of timings. Each key in the returned OrderedDict is a label and the value associated with it is the number of seconds it took between the previous event and this one.

Returns:

Type Description

an OrderedDict of events and how long they took

Source code in ckantools/timer.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def to_dict(self):
    """
    Return an OrderedDict of timings. Each key in the returned OrderedDict is a
    label and the value associated with it is the number of seconds it took between
    the previous event and this one.

    :return: an OrderedDict of events and how long they took
    """
    timings = OrderedDict()
    split = self.start
    for label, date in self.events:
        timings[label] = (date - split).total_seconds()
        split = date
    return timings