summaryrefslogtreecommitdiffstats
path: root/python/pacemaker/_cts/timer.py
blob: 122b70b7117734ae60794b71672c602879937fcf (plain)
1
2
3
4
5
6
7
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
""" Timer-related utilities for CTS """

__all__ = ["Timer"]
__copyright__ = "Copyright 2000-2023 the Pacemaker project contributors"
__license__ = "GNU General Public License version 2 or later (GPLv2+) WITHOUT ANY WARRANTY"

import time

class Timer:
    """ A class for measuring the runtime of some task.  A Timer may be used
        manually or as a context manager, like so:

        with Timer(logger, "SomeTest", "SomeTimer"):
            ...

        A Timer runs from when start() is called until the timer is deleted
        or reset() is called.  There is no explicit stop method.
    """

    def __init__(self, logger, test_name, timer_name):
        """ Create a new Timer instance.

            Arguments:

            logger      -- A Logger instance that can be used to record when
                           the timer stopped
            test_name   -- The name of the test this timer is being run for
            timer_name  -- The name of this timer
        """

        self._logger = logger
        self._start_time = None
        self._test_name = test_name
        self._timer_name = timer_name

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args):
        self._logger.debug("%s:%s runtime: %.2f" % (self._test_name, self._timer_name, self.elapsed))

    def reset(self):
        """ Restart the timer """

        self.start()

    def start(self):
        """ Start the timer """

        self._start_time = time.time()

    @property
    def start_time(self):
        """ When did the timer start? """

        return self._start_time

    @property
    def elapsed(self):
        """ How long has the timer been running for? """

        return time.time() - self._start_time