nano-dev-utils 0.5.8__tar.gz → 1.0.0__tar.gz

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.

Potentially problematic release.


This version of nano-dev-utils might be problematic. Click here for more details.

Files changed (23) hide show
  1. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/workspace.xml +83 -10
  2. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/PKG-INFO +35 -19
  3. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/README.md +34 -18
  4. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/pyproject.toml +1 -1
  5. nano_dev_utils-1.0.0/src/nano_dev_utils/timers.py +68 -0
  6. nano_dev_utils-1.0.0/tests/test_timer.py +313 -0
  7. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/uv.lock +1 -1
  8. nano_dev_utils-0.5.8/src/nano_dev_utils/timers.py +0 -49
  9. nano_dev_utils-0.5.8/tests/test_timer.py +0 -181
  10. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.gitignore +0 -0
  11. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/.gitignore +0 -0
  12. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/inspectionProfiles/profiles_settings.xml +0 -0
  13. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/misc.xml +0 -0
  14. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/modules.xml +0 -0
  15. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/nano_dev_utils.iml +0 -0
  16. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/.idea/vcs.xml +0 -0
  17. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/LICENSE +0 -0
  18. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/src/nano_dev_utils/__init__.py +0 -0
  19. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/src/nano_dev_utils/dynamic_importer.py +0 -0
  20. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/src/nano_dev_utils/release_ports.py +0 -0
  21. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/tests/__init__.py +0 -0
  22. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/tests/test_dynamic_importer.py +0 -0
  23. {nano_dev_utils-0.5.8 → nano_dev_utils-1.0.0}/tests/test_release_ports.py +0 -0
@@ -4,12 +4,7 @@
4
4
  <option name="autoReloadType" value="SELECTIVE" />
5
5
  </component>
6
6
  <component name="ChangeListManager">
7
- <list default="true" id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="corrected return types - complete">
8
- <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
9
- <change beforePath="$PROJECT_DIR$/pyproject.toml" beforeDir="false" afterPath="$PROJECT_DIR$/pyproject.toml" afterDir="false" />
10
- <change beforePath="$PROJECT_DIR$/src/nano_dev_utils/timers.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/nano_dev_utils/timers.py" afterDir="false" />
11
- <change beforePath="$PROJECT_DIR$/tests/test_timer.py" beforeDir="false" afterPath="$PROJECT_DIR$/tests/test_timer.py" afterDir="false" />
12
- </list>
7
+ <list default="true" id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="timers, test_timer - improved overall" />
13
8
  <option name="SHOW_DIALOG" value="false" />
14
9
  <option name="HIGHLIGHT_CONFLICTS" value="true" />
15
10
  <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
@@ -41,12 +36,18 @@
41
36
  "RunOnceActivity.ShowReadmeOnStart": "true",
42
37
  "git-widget-placeholder": "master",
43
38
  "ignore.virus.scanning.warn.message": "true",
44
- "last_opened_file_path": "C:/GitHubWS/nano_dev_utils",
39
+ "last_opened_file_path": "C:/GitHubWS/nano_dev_utils/tests",
45
40
  "settings.editor.selected.configurable": "com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable"
46
41
  }
47
42
  }]]></component>
48
43
  <component name="RecentsManager">
49
44
  <key name="CopyFile.RECENT_KEYS">
45
+ <recent name="C:\GitHubWS\nano_dev_utils\tests" />
46
+ <recent name="C:\GitHubWS\nano_dev_utils" />
47
+ </key>
48
+ <key name="MoveFile.RECENT_KEYS">
49
+ <recent name="C:\GitHubWS\nano_dev_utils\tests" />
50
+ <recent name="C:\GitHubWS\nano_dev_utils\src\nano_dev_utils" />
50
51
  <recent name="C:\GitHubWS\nano_dev_utils" />
51
52
  </key>
52
53
  </component>
@@ -105,9 +106,9 @@
105
106
  </configuration>
106
107
  <recent_temporary>
107
108
  <list>
108
- <item itemvalue="Python tests.Python tests in tests" />
109
109
  <item itemvalue="Python tests.Python tests in tests" />
110
110
  <item itemvalue="Python tests.Python tests in test_timer.py" />
111
+ <item itemvalue="Python tests.Python tests in tests" />
111
112
  <item itemvalue="Python.test_timer" />
112
113
  </list>
113
114
  </recent_temporary>
@@ -216,7 +217,71 @@
216
217
  <option name="project" value="LOCAL" />
217
218
  <updated>1747666293914</updated>
218
219
  </task>
219
- <option name="localTasksCounter" value="12" />
220
+ <task id="LOCAL-00012" summary="+iterations&#10;+version update">
221
+ <option name="closed" value="true" />
222
+ <created>1747666696203</created>
223
+ <option name="number" value="00012" />
224
+ <option name="presentableId" value="LOCAL-00012" />
225
+ <option name="project" value="LOCAL" />
226
+ <updated>1747666696203</updated>
227
+ </task>
228
+ <task id="LOCAL-00013" summary="+pre-commit, ruff &#10;+type-hinting update for Timer">
229
+ <option name="closed" value="true" />
230
+ <created>1747819871928</created>
231
+ <option name="number" value="00013" />
232
+ <option name="presentableId" value="LOCAL-00013" />
233
+ <option name="project" value="LOCAL" />
234
+ <updated>1747819871928</updated>
235
+ </task>
236
+ <task id="LOCAL-00014" summary="+timeout support">
237
+ <option name="closed" value="true" />
238
+ <created>1748164800940</created>
239
+ <option name="number" value="00014" />
240
+ <option name="presentableId" value="LOCAL-00014" />
241
+ <option name="project" value="LOCAL" />
242
+ <updated>1748164800940</updated>
243
+ </task>
244
+ <task id="LOCAL-00015" summary="+updates related to timeout functionality - WIP">
245
+ <option name="closed" value="true" />
246
+ <created>1748164866417</created>
247
+ <option name="number" value="00015" />
248
+ <option name="presentableId" value="LOCAL-00015" />
249
+ <option name="project" value="LOCAL" />
250
+ <updated>1748164866417</updated>
251
+ </task>
252
+ <task id="LOCAL-00016" summary="using self.precision instead of hardcoded value&#10;ongoing unit tests update">
253
+ <option name="closed" value="true" />
254
+ <created>1748165510054</created>
255
+ <option name="number" value="00016" />
256
+ <option name="presentableId" value="LOCAL-00016" />
257
+ <option name="project" value="LOCAL" />
258
+ <updated>1748165510054</updated>
259
+ </task>
260
+ <task id="LOCAL-00017" summary="timer unittests complete">
261
+ <option name="closed" value="true" />
262
+ <created>1748186783462</created>
263
+ <option name="number" value="00017" />
264
+ <option name="presentableId" value="LOCAL-00017" />
265
+ <option name="project" value="LOCAL" />
266
+ <updated>1748186783462</updated>
267
+ </task>
268
+ <task id="LOCAL-00018" summary="timers - only work with perf_counter_ns&#10;test_timer - improved overall">
269
+ <option name="closed" value="true" />
270
+ <created>1748198255817</created>
271
+ <option name="number" value="00018" />
272
+ <option name="presentableId" value="LOCAL-00018" />
273
+ <option name="project" value="LOCAL" />
274
+ <updated>1748198255817</updated>
275
+ </task>
276
+ <task id="LOCAL-00019" summary="timers, test_timer - improved overall">
277
+ <option name="closed" value="true" />
278
+ <created>1748199166818</created>
279
+ <option name="number" value="00019" />
280
+ <option name="presentableId" value="LOCAL-00019" />
281
+ <option name="project" value="LOCAL" />
282
+ <updated>1748199166818</updated>
283
+ </task>
284
+ <option name="localTasksCounter" value="20" />
220
285
  <servers />
221
286
  </component>
222
287
  <component name="Vcs.Log.Tabs.Properties">
@@ -242,6 +307,14 @@
242
307
  <MESSAGE value="minor update" />
243
308
  <MESSAGE value="corrected return type" />
244
309
  <MESSAGE value="corrected return types - complete" />
245
- <option name="LAST_COMMIT_MESSAGE" value="corrected return types - complete" />
310
+ <MESSAGE value="+iterations&#10;+version update" />
311
+ <MESSAGE value="+pre-commit, ruff &#10;+type-hinting update for Timer" />
312
+ <MESSAGE value="+timeout support" />
313
+ <MESSAGE value="+updates related to timeout functionality - WIP" />
314
+ <MESSAGE value="using self.precision instead of hardcoded value&#10;ongoing unit tests update" />
315
+ <MESSAGE value="timer unittests complete" />
316
+ <MESSAGE value="timers - only work with perf_counter_ns&#10;test_timer - improved overall" />
317
+ <MESSAGE value="timers, test_timer - improved overall" />
318
+ <option name="LAST_COMMIT_MESSAGE" value="timers, test_timer - improved overall" />
246
319
  </component>
247
320
  </project>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nano_dev_utils
3
- Version: 0.5.8
3
+ Version: 1.0.0
4
4
  Summary: A collection of small Python utilities for developers.
5
5
  Project-URL: Homepage, https://github.com/yaronday/nano_utils
6
6
  Project-URL: Issues, https://github.com/yaronday/nano_utils/issues
@@ -24,23 +24,33 @@ A collection of small Python utilities for developers.
24
24
 
25
25
  ### `timers.py`
26
26
 
27
- This module provides a `Timer` class for measuring the execution time of code blocks and functions.
27
+ This module provides a `Timer` class for measuring the execution time of code blocks and functions with additional features like timeout control and multi-iteration averaging.
28
28
 
29
29
  #### `Timer` Class
30
30
 
31
31
  * **`__init__(self, precision: int = 4, verbose: bool = False)`**: Initializes a `Timer` instance.
32
- * `precision`: The number of decimal places to record and
33
- display time durations. Defaults to 4.
34
- * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs).
35
- Defaults to `False`.
32
+ * `precision`: The number of decimal places to record and display time durations. Defaults to 4.
33
+ * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs). Defaults to `False`.
36
34
 
37
35
  * **`timeit(
38
- self, iterations: int = 1
36
+ self,
37
+ iterations: int = 1,
38
+ timeout: float | None = None,
39
+ per_iteration: bool = False
39
40
  ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
40
- Decorator that times function execution with automatic unit scaling.
41
- * When the decorated function is called, this decorator records the start and end times,
42
- calculates the average execution time, prints the function name and execution
43
- time (optionally including arguments), and returns the result of the original function.
41
+ Decorator that times function execution with advanced features:
42
+ * `iterations`: Number of times to run the function (for averaging). Defaults to 1.
43
+ * `timeout`: Maximum allowed execution time in seconds. When exceeded:
44
+ * Raises `TimeoutError` immediately
45
+ * **Warning:** The function execution will be aborted mid-operation
46
+ * No return value will be available if timeout occurs
47
+ * `per_iteration`: If True, applies timeout check to each iteration; otherwise checks total time across all iterations.
48
+ * Features:
49
+ * Records execution times
50
+ * Handles timeout conditions
51
+ * Calculates average execution time across iterations
52
+ * Prints the function name and execution time (with optional arguments)
53
+ * Returns the result of the original function (unless timeout occurs)
44
54
 
45
55
  #### Example Usage:
46
56
 
@@ -50,16 +60,22 @@ from nano_dev_utils.timers import Timer
50
60
 
51
61
  timer = Timer(precision=6, verbose=True)
52
62
 
53
-
63
+ # Basic timing
54
64
  @timer.timeit()
55
65
  def my_function(a, b=10):
56
- """A sample function."""
57
- time.sleep(0.1)
58
- return a + b
59
-
60
-
61
- result = my_function(5, b=20)
62
- print(f"Result: {result}")
66
+ """A sample function."""
67
+ time.sleep(0.1)
68
+ return a + b
69
+
70
+ # Advanced usage with timeout and iterations
71
+ @timer.timeit(iterations=5, timeout=0.5, per_iteration=True)
72
+ def critical_function(x):
73
+ """Function with timeout check per iteration."""
74
+ time.sleep(0.08)
75
+ return x * 2
76
+
77
+ result1 = my_function(5, b=20) # Shows args/kwargs and timing
78
+ result2 = critical_function(10) # Runs 5 times with per-iteration timeout
63
79
  ```
64
80
 
65
81
  ### `dynamic_importer.py`
@@ -6,23 +6,33 @@ A collection of small Python utilities for developers.
6
6
 
7
7
  ### `timers.py`
8
8
 
9
- This module provides a `Timer` class for measuring the execution time of code blocks and functions.
9
+ This module provides a `Timer` class for measuring the execution time of code blocks and functions with additional features like timeout control and multi-iteration averaging.
10
10
 
11
11
  #### `Timer` Class
12
12
 
13
13
  * **`__init__(self, precision: int = 4, verbose: bool = False)`**: Initializes a `Timer` instance.
14
- * `precision`: The number of decimal places to record and
15
- display time durations. Defaults to 4.
16
- * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs).
17
- Defaults to `False`.
14
+ * `precision`: The number of decimal places to record and display time durations. Defaults to 4.
15
+ * `verbose`: Optionally displays the function's positional arguments (args) and keyword arguments (kwargs). Defaults to `False`.
18
16
 
19
17
  * **`timeit(
20
- self, iterations: int = 1
18
+ self,
19
+ iterations: int = 1,
20
+ timeout: float | None = None,
21
+ per_iteration: bool = False
21
22
  ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
22
- Decorator that times function execution with automatic unit scaling.
23
- * When the decorated function is called, this decorator records the start and end times,
24
- calculates the average execution time, prints the function name and execution
25
- time (optionally including arguments), and returns the result of the original function.
23
+ Decorator that times function execution with advanced features:
24
+ * `iterations`: Number of times to run the function (for averaging). Defaults to 1.
25
+ * `timeout`: Maximum allowed execution time in seconds. When exceeded:
26
+ * Raises `TimeoutError` immediately
27
+ * **Warning:** The function execution will be aborted mid-operation
28
+ * No return value will be available if timeout occurs
29
+ * `per_iteration`: If True, applies timeout check to each iteration; otherwise checks total time across all iterations.
30
+ * Features:
31
+ * Records execution times
32
+ * Handles timeout conditions
33
+ * Calculates average execution time across iterations
34
+ * Prints the function name and execution time (with optional arguments)
35
+ * Returns the result of the original function (unless timeout occurs)
26
36
 
27
37
  #### Example Usage:
28
38
 
@@ -32,16 +42,22 @@ from nano_dev_utils.timers import Timer
32
42
 
33
43
  timer = Timer(precision=6, verbose=True)
34
44
 
35
-
45
+ # Basic timing
36
46
  @timer.timeit()
37
47
  def my_function(a, b=10):
38
- """A sample function."""
39
- time.sleep(0.1)
40
- return a + b
41
-
42
-
43
- result = my_function(5, b=20)
44
- print(f"Result: {result}")
48
+ """A sample function."""
49
+ time.sleep(0.1)
50
+ return a + b
51
+
52
+ # Advanced usage with timeout and iterations
53
+ @timer.timeit(iterations=5, timeout=0.5, per_iteration=True)
54
+ def critical_function(x):
55
+ """Function with timeout check per iteration."""
56
+ time.sleep(0.08)
57
+ return x * 2
58
+
59
+ result1 = my_function(5, b=20) # Shows args/kwargs and timing
60
+ result2 = critical_function(10) # Runs 5 times with per-iteration timeout
45
61
  ```
46
62
 
47
63
  ### `dynamic_importer.py`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "nano_dev_utils"
3
- version = "0.5.8"
3
+ version = "1.0.0"
4
4
 
5
5
  authors = [
6
6
  { name="Yaron Dayan", email="yaronday77@gmail.com" },
@@ -0,0 +1,68 @@
1
+ from functools import wraps
2
+ import time
3
+ from typing import Callable, ParamSpec, TypeVar
4
+
5
+ P = ParamSpec('P')
6
+ R = TypeVar('R')
7
+
8
+
9
+ class Timer:
10
+ def __init__(self, precision: int = 4, verbose: bool = False):
11
+ self.precision = precision
12
+ self.verbose = verbose
13
+ self.units = [(1e9, 's'), (1e6, 'ms'), (1e3, 'μs'), (1.0, 'ns')]
14
+
15
+ def timeit(
16
+ self,
17
+ iterations: int = 1,
18
+ timeout: float | None = None,
19
+ per_iteration: bool = False,
20
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]:
21
+ """Decorator that times function execution with optional timeout support."""
22
+
23
+ def decorator(func: Callable[P, R]) -> Callable[P, R | None]:
24
+ @wraps(func)
25
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
26
+ total_elapsed_ns = 0
27
+ result: R | None = None
28
+
29
+ for i in range(1, iterations + 1):
30
+ start_ns = time.perf_counter_ns()
31
+ result = func(*args, **kwargs)
32
+ duration_ns = time.perf_counter_ns() - start_ns
33
+ total_elapsed_ns += duration_ns
34
+
35
+ if timeout is not None:
36
+ if per_iteration:
37
+ duration_s = duration_ns / 1e9
38
+ if duration_s > timeout:
39
+ raise TimeoutError(
40
+ f'{func.__name__} exceeded '
41
+ f'{timeout:.{self.precision}f}s on '
42
+ f'iteration {i} (took '
43
+ f'{duration_s:.{self.precision}f}s)'
44
+ )
45
+ else:
46
+ total_duration_s = total_elapsed_ns / 1e9
47
+ if total_duration_s > timeout:
48
+ raise TimeoutError(
49
+ f'{func.__name__} exceeded {timeout:.{self.precision}f}s '
50
+ f'after {i} iterations (took {total_duration_s:.{self.precision}f}s)'
51
+ )
52
+
53
+ avg_elapsed_ns = total_elapsed_ns / iterations
54
+ value, unit = next(
55
+ (avg_elapsed_ns / div, u)
56
+ for div, u in self.units
57
+ if avg_elapsed_ns >= div or u == 'ns'
58
+ )
59
+ extra_info = f'{args} {kwargs} ' if self.verbose else ''
60
+ iter_info = f' (avg. over {iterations} runs)' if iterations > 1 else ''
61
+ print(
62
+ f'{func.__name__} {extra_info}took {value:.{self.precision}f} [{unit}]{iter_info}'
63
+ )
64
+ return result
65
+
66
+ return wrapper
67
+
68
+ return decorator
@@ -0,0 +1,313 @@
1
+ import threading
2
+ import pytest
3
+ from src.nano_dev_utils.timers import Timer
4
+
5
+
6
+ def test_initialization():
7
+ timer = Timer()
8
+ assert timer.precision == 4
9
+ assert not timer.verbose
10
+
11
+ timer_custom = Timer(precision=6, verbose=True)
12
+ assert timer_custom.precision == 6
13
+ assert timer_custom.verbose
14
+
15
+
16
+ def test_timeit_simple(mocker):
17
+ mock_print = mocker.patch('builtins.print')
18
+ mock_time = mocker.patch('time.perf_counter_ns', side_effect=[0, 9.23467e5])
19
+ timer = Timer(precision=2)
20
+
21
+ @timer.timeit()
22
+ def sample_function():
23
+ return 'result'
24
+
25
+ result = sample_function()
26
+ assert result == 'result'
27
+ mock_time.assert_any_call()
28
+ mock_print.assert_called_once_with('sample_function took 923.47 [μs]')
29
+
30
+
31
+ def test_timeit_no_args_kwargs(mocker):
32
+ mock_print = mocker.patch('builtins.print')
33
+ mock_time = mocker.patch('time.perf_counter_ns', side_effect=[1.0, 1.5])
34
+ timer = Timer(precision=2, verbose=True)
35
+
36
+ @timer.timeit()
37
+ def yet_another_function():
38
+ return 'yet another result'
39
+
40
+ result = yet_another_function()
41
+ assert result == 'yet another result'
42
+ mock_time.assert_any_call()
43
+ mock_print.assert_called_once_with('yet_another_function () {} took 0.50 [ns]')
44
+
45
+
46
+ def test_multithreaded_timing(mocker):
47
+ """Test timer works correctly across threads"""
48
+ mock_print = mocker.patch('builtins.print')
49
+ sim_time_us = 1 # μs
50
+ sim_time_ns = sim_time_us * 1e3
51
+ num_of_threads = 4
52
+ mocker.patch(
53
+ 'time.perf_counter_ns',
54
+ side_effect=[0, sim_time_ns] * num_of_threads,
55
+ autospec=True,
56
+ )
57
+
58
+ timer = Timer()
59
+ results = []
60
+
61
+ @timer.timeit()
62
+ def threaded_operation():
63
+ return threading.get_ident()
64
+
65
+ def run_in_thread():
66
+ results.append(threaded_operation())
67
+
68
+ threads = [threading.Thread(target=run_in_thread) for _ in range(num_of_threads)]
69
+
70
+ for t in threads:
71
+ t.start()
72
+ for t in threads:
73
+ t.join()
74
+
75
+ assert mock_print.call_count == num_of_threads
76
+ assert len(set(results)) == num_of_threads
77
+
78
+ for call_args in mock_print.call_args_list:
79
+ assert f'took {sim_time_us:.{timer.precision}f} [μs]' in call_args[0][0]
80
+
81
+
82
+ def test_verbose_mode(mocker):
83
+ """Test that verbose mode includes positional and
84
+ keyword arguments in output and preserves the wrapped func result"""
85
+ mock_print = mocker.patch('builtins.print')
86
+ mocker.patch('time.perf_counter_ns', side_effect=[1e4, 5.23456e4])
87
+ verbose_timer = Timer(verbose=True)
88
+
89
+ @verbose_timer.timeit()
90
+ def func_with_args(a, b, c=3):
91
+ return a + b + c
92
+
93
+ res = func_with_args(1, 2, c=4)
94
+ output = mock_print.call_args[0][0]
95
+ assert '(1, 2)' in output # checking positional args
96
+ assert "'c': 4" in output # checking kwargs
97
+ mock_print.assert_called_once_with(
98
+ "func_with_args (1, 2) {'c': 4} took 42.3456 [μs]"
99
+ )
100
+ assert res == 7 # checking returned value preservation
101
+
102
+
103
+ def test_nested_timers(mocker):
104
+ """Test that nested timers work correctly"""
105
+ outer_start = 1000
106
+ inner_start = 1100
107
+ inner_end = 1200
108
+ outer_end = 1300
109
+ mocker.patch(
110
+ 'time.perf_counter_ns',
111
+ side_effect=[
112
+ outer_start,
113
+ inner_start,
114
+ inner_end,
115
+ outer_end,
116
+ ],
117
+ )
118
+
119
+ mock_print = mocker.patch('builtins.print')
120
+ timer = Timer()
121
+
122
+ @timer.timeit()
123
+ def outer():
124
+ @timer.timeit()
125
+ def inner():
126
+ pass
127
+
128
+ return inner()
129
+
130
+ outer()
131
+
132
+ # Should have two print calls (inner and outer)
133
+ assert mock_print.call_count == 2
134
+ inner_output = mock_print.call_args_list[0][0][0]
135
+ outer_output = mock_print.call_args_list[1][0][0]
136
+
137
+ inner_duration = float(inner_output.split('took ')[1].split(' [')[0])
138
+ outer_duration = float(outer_output.split('took ')[1].split(' [')[0])
139
+
140
+ assert inner_duration == inner_end - inner_start
141
+ assert outer_duration == outer_end - outer_start
142
+ assert outer_duration > inner_duration
143
+
144
+
145
+ def test_unit_scaling(mocker):
146
+ """Test the time unit selection logic directly"""
147
+ mock_print = mocker.patch('builtins.print')
148
+
149
+ boundary_cases = [
150
+ (1e3 - 1, 'ns'),
151
+ (1e3, 'μs'),
152
+ (1e6 - 1, 'μs'),
153
+ (1e6, 'ms'),
154
+ (1e9 - 1, 'ms'),
155
+ (1e9, 's'),
156
+ ]
157
+
158
+ for ns, expected_unit in boundary_cases:
159
+ mocker.patch('time.perf_counter_ns', side_effect=[0, ns])
160
+ timer = Timer(precision=2)
161
+
162
+ @timer.timeit()
163
+ def dummy():
164
+ pass
165
+
166
+ dummy()
167
+ printed_output = mock_print.call_args[0][0]
168
+ assert expected_unit in printed_output, (
169
+ f"Failed for {ns:,}ns → Expected '{expected_unit}' in output. "
170
+ f'Got: {printed_output}'
171
+ )
172
+
173
+
174
+ def test_function_metadata_preserved():
175
+ """Test that function metadata (name, docstring) is preserved"""
176
+ timer = Timer(precision=3)
177
+
178
+ @timer.timeit()
179
+ def dummy_func():
180
+ """Test docstring"""
181
+ pass
182
+
183
+ assert dummy_func.__name__ == 'dummy_func'
184
+ assert dummy_func.__doc__ == 'Test docstring'
185
+
186
+
187
+ def test_timeit_with_iterations(mocker):
188
+ mock_print = mocker.patch('builtins.print')
189
+
190
+ k = 3
191
+ sim_times_ns = [0, 1e3, 0, 2e3, 0, 3e3]
192
+ mock_time = mocker.patch(
193
+ 'time.perf_counter_ns',
194
+ side_effect=sim_times_ns,
195
+ autospec=True,
196
+ )
197
+
198
+ timer = Timer(precision=2)
199
+
200
+ @timer.timeit(iterations=k)
201
+ def sample_function():
202
+ return 'done'
203
+
204
+ result = sample_function()
205
+
206
+ assert result == 'done'
207
+ mock_time.assert_any_call()
208
+
209
+ mock_print.assert_called_once_with(
210
+ f'sample_function took {sum(sim_times_ns) / 3e3:.{timer.precision}f} [μs] (avg. over {k} runs)'
211
+ )
212
+
213
+
214
+ def test_timeout_single_iteration(mocker):
215
+ cfg_timeout_s = 0.1
216
+ duration_s = cfg_timeout_s + 0.1
217
+ current_time_ns = 0.0
218
+ duration_ns = duration_s * 1e9
219
+
220
+ mocker.patch(
221
+ 'time.perf_counter_ns',
222
+ side_effect=[0.0, duration_ns],
223
+ autospec=True,
224
+ )
225
+ timer = Timer(precision=6, verbose=True)
226
+
227
+ @timer.timeit(timeout=cfg_timeout_s)
228
+ def timed_function():
229
+ nonlocal current_time_ns
230
+ current_time_ns += duration_ns
231
+
232
+ with pytest.raises(TimeoutError) as exc_info:
233
+ timed_function()
234
+
235
+ assert f'took {duration_s:.{timer.precision}f}s' in str(exc_info.value)
236
+
237
+
238
+ def test_timeout_multiple_iterations(mocker):
239
+ sim_time_per_iter_s = 0.3
240
+ sim_time_per_iter_ns = sim_time_per_iter_s * 1e9
241
+
242
+ k = 5
243
+ timeout_threshold = (k - 1) * sim_time_per_iter_s - 0.1
244
+
245
+ mocker.patch(
246
+ 'time.perf_counter_ns',
247
+ side_effect=[sim_time_per_iter_ns * count for count in range(2 * k - 1)],
248
+ autospec=True,
249
+ )
250
+
251
+ timer = Timer(precision=6, verbose=True)
252
+
253
+ @timer.timeit(iterations=k, timeout=timeout_threshold)
254
+ def func(duration: float) -> str:
255
+ return f'Function completed in simulated {duration}s'
256
+
257
+ with pytest.raises(TimeoutError) as exc_info:
258
+ func(sim_time_per_iter_s)
259
+
260
+ expected_timeout_val = f'{timeout_threshold:.{timer.precision}f}s'
261
+ expected_taken_val = f'{(sim_time_per_iter_s * (k - 1)):.{timer.precision}f}s'
262
+
263
+ expected_message_template = (
264
+ f'func exceeded {expected_timeout_val} after {k - 1} iterations '
265
+ f'(took {expected_taken_val})'
266
+ )
267
+
268
+ assert str(exc_info.value) == expected_message_template
269
+
270
+
271
+ def test_timeout_per_iteration(mocker):
272
+ sim_time_s = 0.2
273
+ cfg_timeout = 0.1
274
+ mocker.patch(
275
+ 'time.perf_counter_ns', side_effect=[0.0, sim_time_s * 1e9], autospec=True
276
+ )
277
+
278
+ timer = Timer(precision=6, verbose=True)
279
+
280
+ @timer.timeit(iterations=5, timeout=cfg_timeout, per_iteration=True)
281
+ def func(duration: float) -> str:
282
+ return f'Function completed in simulated {duration}s'
283
+
284
+ with pytest.raises(TimeoutError) as exc_info:
285
+ func(sim_time_s)
286
+
287
+ assert (
288
+ f'exceeded {cfg_timeout:.{timer.precision}f}s on iteration 1 '
289
+ f'(took {sim_time_s:.{timer.precision}f}s)'
290
+ ) in str(exc_info.value)
291
+
292
+
293
+ def test_timeout_with_fast_function(mocker):
294
+ mock_print = mocker.patch('builtins.print')
295
+ sim_time_ms = 50.1
296
+ sim_time_s = sim_time_ms / 1e3
297
+
298
+ mocker.patch(
299
+ 'time.perf_counter_ns', side_effect=[0, sim_time_ms * 1e6], autospec=True
300
+ )
301
+
302
+ timer = Timer(precision=4)
303
+
304
+ @timer.timeit(timeout=1.0)
305
+ def func(duration: float) -> str:
306
+ return f'Function completed in simulated {duration}s'
307
+
308
+ result = func(sim_time_s)
309
+
310
+ mock_print.assert_called_once_with(
311
+ f'func took {sim_time_ms:.{timer.precision}f} [ms]'
312
+ )
313
+ assert result == f'Function completed in simulated {sim_time_s}s'
@@ -31,7 +31,7 @@ wheels = [
31
31
 
32
32
  [[package]]
33
33
  name = "nano-dev-utils"
34
- version = "0.5.7"
34
+ version = "0.5.8"
35
35
  source = { editable = "." }
36
36
 
37
37
  [package.optional-dependencies]
@@ -1,49 +0,0 @@
1
- from functools import wraps
2
- import time
3
- from typing import Callable, ParamSpec, TypeVar
4
-
5
- P = ParamSpec('P')
6
- R = TypeVar('R')
7
-
8
-
9
- class Timer:
10
- def __init__(self, precision=4, verbose=False):
11
- self.precision = precision
12
- self.verbose = verbose
13
- self.units = [(1e9, 's'), (1e6, 'ms'), (1e3, 'μs'), (1.0, 'ns')]
14
-
15
- def timeit(
16
- self, iterations: int = 1
17
- ) -> Callable[[Callable[P, R]], Callable[P, R | None]]:
18
- def decorator(func: Callable[P, R]) -> Callable[P, R | None]:
19
- """Decorator that times function execution with automatic unit scaling and averaging."""
20
-
21
- @wraps(func)
22
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R | None:
23
- total_elapsed = 0
24
- result = None
25
-
26
- for _ in range(iterations):
27
- start = time.perf_counter_ns()
28
- result = func(*args, **kwargs)
29
- total_elapsed += time.perf_counter_ns() - start
30
-
31
- avg_elapsed = total_elapsed / iterations
32
- value = avg_elapsed
33
- unit = 'ns'
34
-
35
- for divisor, unit in self.units:
36
- if avg_elapsed >= divisor or unit == 'ns':
37
- value = avg_elapsed / divisor
38
- break
39
-
40
- extra_info = f'{args} {kwargs} ' if self.verbose else ''
41
- iter_info = f' (avg over {iterations} runs)' if iterations > 1 else ''
42
- print(
43
- f'{func.__name__} {extra_info}took {value:.{self.precision}f} [{unit}]{iter_info}'
44
- )
45
- return result
46
-
47
- return wrapper
48
-
49
- return decorator
@@ -1,181 +0,0 @@
1
- import threading
2
- import time
3
- from src.nano_dev_utils.timers import Timer
4
-
5
-
6
- def test_initialization():
7
- timer = Timer()
8
- assert timer.precision == 4
9
- assert not timer.verbose
10
-
11
- timer_custom = Timer(precision=6, verbose=True)
12
- assert timer_custom.precision == 6
13
- assert timer_custom.verbose
14
-
15
-
16
- def test_timeit_simple(mocker):
17
- mock_print = mocker.patch('builtins.print')
18
- mock_time = mocker.patch('time.perf_counter_ns', side_effect=[0, 9.23467e5])
19
- timer = Timer(precision=2)
20
-
21
- @timer.timeit()
22
- def sample_function():
23
- return 'result'
24
-
25
- result = sample_function()
26
- assert result == 'result'
27
- mock_time.assert_any_call()
28
- mock_print.assert_called_once_with('sample_function took 923.47 [μs]')
29
-
30
-
31
- def test_timeit_no_args_kwargs(mocker):
32
- mock_print = mocker.patch('builtins.print')
33
- mock_time = mocker.patch('time.perf_counter_ns', side_effect=[1.0, 1.5])
34
- timer = Timer(precision=2, verbose=True)
35
-
36
- @timer.timeit()
37
- def yet_another_function():
38
- return 'yet another result'
39
-
40
- result = yet_another_function()
41
- assert result == 'yet another result'
42
- mock_time.assert_any_call()
43
- mock_print.assert_called_once_with('yet_another_function () {} took 0.50 [ns]')
44
-
45
-
46
- def test_multithreaded_timing(mocker):
47
- """Test timer works correctly across threads"""
48
- mock_print = mocker.patch('builtins.print')
49
- timer = Timer()
50
- results = []
51
-
52
- @timer.timeit()
53
- def threaded_operation():
54
- time.sleep(0.1)
55
- return threading.get_ident()
56
-
57
- def run_in_thread():
58
- results.append(threaded_operation())
59
-
60
- threads = [threading.Thread(target=run_in_thread) for _ in range(3)]
61
-
62
- for t in threads:
63
- t.start()
64
- for t in threads:
65
- t.join()
66
-
67
- # Should have 3 print calls (one per thread)
68
- assert mock_print.call_count == 3
69
- # All thread IDs should be different
70
- assert len(set(results)) == 3
71
-
72
-
73
- def test_verbose_mode(mocker):
74
- """Test that verbose mode includes positional and
75
- keyword arguments in output and preserves the wrapped func result"""
76
- mock_print = mocker.patch('builtins.print')
77
- mocker.patch('time.perf_counter_ns', side_effect=[1e4, 5.23456e4])
78
- verbose_timer = Timer(verbose=True)
79
-
80
- @verbose_timer.timeit()
81
- def func_with_args(a, b, c=3):
82
- return a + b + c
83
-
84
- res = func_with_args(1, 2, c=4)
85
- output = mock_print.call_args[0][0]
86
- assert '(1, 2)' in output # checking positional args
87
- assert "'c': 4" in output # checking kwargs
88
- mock_print.assert_called_once_with(
89
- "func_with_args (1, 2) {'c': 4} took 42.3456 [μs]"
90
- )
91
- assert res == 7 # checking returned value preservation
92
-
93
-
94
- def test_nested_timers(mocker):
95
- """Test that nested timers work correctly"""
96
- mock_print = mocker.patch('builtins.print')
97
- timer = Timer()
98
-
99
- @timer.timeit()
100
- def outer():
101
- @timer.timeit()
102
- def inner():
103
- time.sleep(0.1)
104
-
105
- return inner()
106
-
107
- outer()
108
-
109
- # Should have two print calls (inner and outer)
110
- assert mock_print.call_count == 2
111
- inner_output = mock_print.call_args_list[0][0][0]
112
- outer_output = mock_print.call_args_list[1][0][0]
113
-
114
- inner_time = float(inner_output.split('took ')[1].split(' [')[0])
115
- outer_time = float(outer_output.split('took ')[1].split(' [')[0])
116
-
117
- assert outer_time > inner_time
118
-
119
-
120
- def test_unit_scaling(mocker):
121
- """Test the time unit selection logic directly"""
122
- mock_print = mocker.patch('builtins.print')
123
-
124
- boundary_cases = [
125
- (1e3 - 1, 'ns'),
126
- (1e3, 'μs'),
127
- (1e6 - 1, 'μs'),
128
- (1e6, 'ms'),
129
- (1e9 - 1, 'ms'),
130
- (1e9, 's'),
131
- ]
132
-
133
- for ns, expected_unit in boundary_cases:
134
- mocker.patch('time.perf_counter_ns', side_effect=[0, ns])
135
- timer = Timer(precision=2)
136
-
137
- @timer.timeit()
138
- def dummy():
139
- pass
140
-
141
- dummy()
142
- printed_output = mock_print.call_args[0][0]
143
- assert expected_unit in printed_output, (
144
- f"Failed for {ns:,}ns → Expected '{expected_unit}' in output. "
145
- f'Got: {printed_output}'
146
- )
147
-
148
-
149
- def test_function_metadata_preserved():
150
- """Test that function metadata (name, docstring) is preserved"""
151
- timer = Timer(precision=3)
152
-
153
- @timer.timeit()
154
- def dummy_func():
155
- """Test docstring"""
156
- pass
157
-
158
- assert dummy_func.__name__ == 'dummy_func'
159
- assert dummy_func.__doc__ == 'Test docstring'
160
-
161
-
162
- def test_timeit_with_iterations(mocker):
163
- mock_print = mocker.patch('builtins.print')
164
- mock_time = mocker.patch(
165
- 'time.perf_counter_ns', side_effect=[0, 1000, 0, 2000, 0, 3000]
166
- )
167
-
168
- timer = Timer(precision=2)
169
-
170
- @timer.timeit(iterations=3)
171
- def sample_function():
172
- return 'done'
173
-
174
- result = sample_function()
175
-
176
- assert result == 'done'
177
- mock_time.assert_any_call()
178
-
179
- mock_print.assert_called_once_with(
180
- 'sample_function took 2.00 [μs] (avg over 3 runs)'
181
- )
File without changes