1
|
|
|
# Copyright (C) 2020 Greenbone Networks GmbH |
2
|
|
|
# |
3
|
|
|
# SPDX-License-Identifier: GPL-2.0-or-later |
4
|
|
|
# |
5
|
|
|
# This program is free software; you can redistribute it and/or |
6
|
|
|
# modify it under the terms of the GNU General Public License |
7
|
|
|
# as published by the Free Software Foundation; either version 2 |
8
|
|
|
# of the 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 General Public License for more details. |
14
|
|
|
# |
15
|
|
|
# You should have received a copy of the GNU General Public License |
16
|
|
|
# along with this program; if not, write to the Free Software |
17
|
|
|
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
18
|
|
|
|
19
|
|
|
import time |
20
|
|
|
import logging |
21
|
|
|
|
22
|
|
|
from ospd.errors import OspdError |
23
|
|
|
|
24
|
|
|
|
25
|
|
|
logger = logging.getLogger(__name__) |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
class TimerError(OspdError): |
29
|
|
|
""" Timer errors """ |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
class Timer: |
33
|
|
|
def __init__( |
34
|
|
|
self, |
35
|
|
|
name: str = None, |
36
|
|
|
text: str = "{}: Elapsed time: {:0.4f} seconds", |
37
|
|
|
logger=logger.debug, # pylint: disable=redefined-outer-name |
38
|
|
|
): |
39
|
|
|
self._start_time = None |
40
|
|
|
self._name = name |
41
|
|
|
self._text = text |
42
|
|
|
self._logger = logger |
43
|
|
|
|
44
|
|
|
def __enter__(self): |
45
|
|
|
self.start() |
46
|
|
|
return self |
47
|
|
|
|
48
|
|
|
def __exit__(self, exc_type, exc_value, exc_tb): |
49
|
|
|
self.stop() |
50
|
|
|
|
51
|
|
|
@staticmethod |
52
|
|
|
def create(name) -> "Timer": |
53
|
|
|
timer = Timer(name) |
54
|
|
|
timer.start() |
55
|
|
|
return timer |
56
|
|
|
|
57
|
|
|
def start(self): |
58
|
|
|
"""Start a new timer""" |
59
|
|
|
self._start_time = time.perf_counter() |
60
|
|
|
|
61
|
|
|
def stop(self): |
62
|
|
|
if not self._start_time: |
63
|
|
|
raise TimerError('Timer is not running.') |
64
|
|
|
|
65
|
|
|
duration = time.perf_counter() - self._start_time |
66
|
|
|
|
67
|
|
|
if self._logger: |
68
|
|
|
self._logger(self._text.format(self._name, duration)) |
69
|
|
|
|
70
|
|
|
return duration |
71
|
|
|
|