ospd.timer.Timer.__exit__()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 4
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
# Copyright (C) 2014-2021 Greenbone Networks GmbH
2
#
3
# SPDX-License-Identifier: AGPL-3.0-or-later
4
#
5
# This program is free software: you can redistribute it and/or modify
6
# it under the terms of the GNU Affero General Public License as
7
# published by the Free Software Foundation, either version 3 of the
8
# License, or (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU Affero General Public License for more details.
14
#
15
# You should have received a copy of the GNU Affero General Public License
16
# along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18
import time
19
import logging
20
21
from ospd.errors import OspdError
22
23
24
logger = logging.getLogger(__name__)
25
26
27
class TimerError(OspdError):
28
    """Timer errors"""
29
30
31
class Timer:
32
    def __init__(
33
        self,
34
        name: str = None,
35
        text: str = "{}: Elapsed time: {:0.4f} seconds",
36
        logger=logger.debug,  # pylint: disable=redefined-outer-name
37
    ):
38
        self._start_time = None
39
        self._name = name
40
        self._text = text
41
        self._logger = logger
42
43
    def __enter__(self):
44
        self.start()
45
        return self
46
47
    def __exit__(self, exc_type, exc_value, exc_tb):
48
        self.stop()
49
50
    @staticmethod
51
    def create(name) -> "Timer":
52
        timer = Timer(name)
53
        timer.start()
54
        return timer
55
56
    def start(self):
57
        """Start a new timer"""
58
        self._start_time = time.perf_counter()
59
60
    def stop(self):
61
        if not self._start_time:
62
            raise TimerError('Timer is not running.')
63
64
        duration = time.perf_counter() - self._start_time
65
66
        if self._logger:
67
            self._logger(self._text.format(self._name, duration))
68
69
        return duration
70