bs-python-utils 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,76 @@
1
+ """
2
+ utilities to time code
3
+ """
4
+
5
+ import time
6
+ from functools import wraps
7
+ from typing import Any, Callable, Iterable
8
+
9
+
10
+ def timeit(func: Callable) -> Callable:
11
+ """
12
+ Decorator to time a function
13
+ """
14
+
15
+ @wraps(func)
16
+ def wrapper(*args: Iterable, **kwargs: dict) -> Any:
17
+ start = time.perf_counter()
18
+ result = func(*args, **kwargs)
19
+ end = time.perf_counter()
20
+ print(f"{func.__name__} executed in {end - start:.6f} seconds")
21
+ return result
22
+
23
+ return wrapper
24
+
25
+
26
+ class Timer:
27
+ """
28
+ A timer that can be started, stopped, and reset as needed by the user.
29
+ It keeps track of the total elapsed time in the `elapsed` attribute::
30
+
31
+ with Timer() as t:
32
+ ....
33
+ print(f"... took {t.elapsed} seconds")
34
+
35
+ use `Timer(time.process_time)` to get only CPU time.
36
+
37
+ can also do::
38
+
39
+ t = Timer()
40
+ t.start()
41
+ t.stop()
42
+ t.start() # will add to the same counter
43
+ t.stop()
44
+ print(f"{t.elapsed} seconds total")
45
+ """
46
+
47
+ def __init__(self, func: Callable = time.perf_counter) -> None:
48
+ self.elapsed = 0.0
49
+ self._func = func
50
+ self._start = None
51
+
52
+ def start(self) -> None:
53
+ if self._start is not None:
54
+ raise RuntimeError("Already started")
55
+ self._start = self._func()
56
+
57
+ def stop(self) -> None:
58
+ if self._start is None:
59
+ raise RuntimeError("Not started")
60
+ end = self._func()
61
+ self.elapsed += end - self._start
62
+ self._start = None
63
+
64
+ def reset(self) -> None:
65
+ self.elapsed = 0.0
66
+
67
+ @property
68
+ def running(self) -> bool:
69
+ return self._start is not None
70
+
71
+ def __enter__(self) -> Any:
72
+ self.start()
73
+ return self
74
+
75
+ def __exit__(self, *args: Iterable) -> None:
76
+ self.stop()
File without changes