pyTooling.Timer

pyTooling/Timer/__init__.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# ==================================================================================================================== #
#              _____           _ _             _____ _                                                                 #
#   _ __  _   |_   _|__   ___ | (_)_ __   __ _|_   _(_)_ __ ___   ___ _ __                                             #
#  | '_ \| | | || |/ _ \ / _ \| | | '_ \ / _` | | | | | '_ ` _ \ / _ \ '__|                                            #
#  | |_) | |_| || | (_) | (_) | | | | | | (_| |_| | | | | | | | |  __/ |                                               #
#  | .__/ \__, ||_|\___/ \___/|_|_|_| |_|\__, (_)_| |_|_| |_| |_|\___|_|                                               #
#  |_|    |___/                          |___/                                                                         #
# ==================================================================================================================== #
# Authors:                                                                                                             #
#   Patrick Lehmann                                                                                                    #
#                                                                                                                      #
# License:                                                                                                             #
# ==================================================================================================================== #
# Copyright 2017-2024 Patrick Lehmann - Bötzingen, Germany                                                             #
#                                                                                                                      #
# Licensed under the Apache License, Version 2.0 (the "License");                                                      #
# you may not use this file except in compliance with the License.                                                     #
# You may obtain a copy of the License at                                                                              #
#                                                                                                                      #
#   http://www.apache.org/licenses/LICENSE-2.0                                                                         #
#                                                                                                                      #
# Unless required by applicable law or agreed to in writing, software                                                  #
# distributed under the License is distributed on an "AS IS" BASIS,                                                    #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.                                             #
# See the License for the specific language governing permissions and                                                  #
# limitations under the License.                                                                                       #
#                                                                                                                      #
# SPDX-License-Identifier: Apache-2.0                                                                                  #
# ==================================================================================================================== #
#
"""
A timer and stopwatch to measure execution time.

.. hint:: See :ref:`high-level help <TIMER>` for explanations and usage examples.
"""
from time   import perf_counter_ns
from typing import List, Optional as Nullable, Dict
# Python 3.11: use Self if returning the own object: , Self

try:
	from pyTooling.Decorators  import export, readonly
	from pyTooling.MetaClasses import SlottedObject
except (ImportError, ModuleNotFoundError):  # pragma: no cover
	print("[pyTooling.Timer] Could not import from 'pyTooling.*'!")

	try:
		from Decorators          import export, readonly
		from MetaClasses         import SlottedObject
	except (ImportError, ModuleNotFoundError) as ex:  # pragma: no cover
		print("[pyTooling.Timer] Could not import directly!")
		raise ex


@export
class Timer(SlottedObject):
	"""
	Undocumented.

	.. todo::TIMER::Timer Needs class documentation.
	"""

	_timers: Dict[str, 'Timer']

	_startTime: Nullable[int]
	_resumeTime: Nullable[int]
	_pauseTime: int
	_stopTime: int
	_diffTime: int
	_diffTimes: List[int]

	def __init__(self) -> None:
		self._timers = {}

		self._startTime = None
		self._resumeTime = None
		self._diffTimes = []

	def __enter__(self):  # Python 3.11: -> Self:
		self.Start()
		return self

	def __exit__(self, exc_type, exc_val, exc_tb):
		self.Stop()

	def Start(self):
		self._resumeTime = self._startTime = perf_counter_ns()

	def Stop(self):
		if self._startTime is None:
			raise Exception(f"Timer was never started.")

		self._stopTime = perf_counter_ns()
		self._diffTime = self._stopTime - self._startTime

		return self._diffTime / 1e9

	def Pause(self):
		self._pauseTime = perf_counter_ns()

		if self._resumeTime is None:
			raise Exception(f"Timer was not (re-)started.")

		diff = self._pauseTime - self._resumeTime
		self._diffTimes.append(diff)
		self._resumeTime = None

		return diff / 1e9

	def Continue(self):
		self._resumeTime = perf_counter_ns()

	@readonly
	def Duration(self) -> float:
		return self._diffTime / 1e9

	@readonly
	def DurationMS(self) -> float:
		return self._diffTime / 1e6

	@readonly
	def DurationUS(self) -> float:
		return self._diffTime / 1e3