nano-dev-utils 0.5.7__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 (24) hide show
  1. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.idea/nano_dev_utils.iml +3 -1
  2. nano_dev_utils-1.0.0/.idea/workspace.xml +320 -0
  3. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/PKG-INFO +39 -21
  4. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/README.md +38 -20
  5. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/pyproject.toml +1 -1
  6. nano_dev_utils-1.0.0/src/nano_dev_utils/timers.py +68 -0
  7. nano_dev_utils-1.0.0/tests/test_timer.py +313 -0
  8. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/uv.lock +1 -1
  9. nano_dev_utils-0.5.7/.idea/workspace.xml +0 -155
  10. nano_dev_utils-0.5.7/src/nano_dev_utils/timers.py +0 -38
  11. nano_dev_utils-0.5.7/tests/test_timer.py +0 -159
  12. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.gitignore +0 -0
  13. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.idea/.gitignore +0 -0
  14. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.idea/inspectionProfiles/profiles_settings.xml +0 -0
  15. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.idea/misc.xml +0 -0
  16. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.idea/modules.xml +0 -0
  17. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/.idea/vcs.xml +0 -0
  18. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/LICENSE +0 -0
  19. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/src/nano_dev_utils/__init__.py +0 -0
  20. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/src/nano_dev_utils/dynamic_importer.py +0 -0
  21. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/src/nano_dev_utils/release_ports.py +0 -0
  22. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/tests/__init__.py +0 -0
  23. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/tests/test_dynamic_importer.py +0 -0
  24. {nano_dev_utils-0.5.7 → nano_dev_utils-1.0.0}/tests/test_release_ports.py +0 -0
@@ -1,7 +1,9 @@
1
1
  <?xml version="1.0" encoding="UTF-8"?>
2
2
  <module type="PYTHON_MODULE" version="4">
3
3
  <component name="NewModuleRootManager">
4
- <content url="file://$MODULE_DIR$" />
4
+ <content url="file://$MODULE_DIR$">
5
+ <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
6
+ </content>
5
7
  <orderEntry type="jdk" jdkName="Python 3.10 (nano_dev_utils)" jdkType="Python SDK" />
6
8
  <orderEntry type="sourceFolder" forTests="false" />
7
9
  </component>
@@ -0,0 +1,320 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="timers, test_timer - improved overall" />
8
+ <option name="SHOW_DIALOG" value="false" />
9
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
10
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
11
+ <option name="LAST_RESOLUTION" value="IGNORE" />
12
+ </component>
13
+ <component name="Git.Settings">
14
+ <option name="RECENT_BRANCH_BY_REPOSITORY">
15
+ <map>
16
+ <entry key="$PROJECT_DIR$" value="FI" />
17
+ </map>
18
+ </option>
19
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
20
+ </component>
21
+ <component name="ProjectColorInfo">{
22
+ &quot;customColor&quot;: &quot;&quot;,
23
+ &quot;associatedIndex&quot;: 5
24
+ }</component>
25
+ <component name="ProjectId" id="2wVV0HQbcggEgX5PEayC1Mcx9Gd" />
26
+ <component name="ProjectViewState">
27
+ <option name="hideEmptyMiddlePackages" value="true" />
28
+ <option name="showLibraryContents" value="true" />
29
+ <option name="showMembers" value="true" />
30
+ </component>
31
+ <component name="PropertiesComponent"><![CDATA[{
32
+ "keyToString": {
33
+ "Python tests.Python tests in test_timer.py.executor": "Run",
34
+ "Python tests.Python tests in tests.executor": "Run",
35
+ "Python.test_timer.executor": "Run",
36
+ "RunOnceActivity.ShowReadmeOnStart": "true",
37
+ "git-widget-placeholder": "master",
38
+ "ignore.virus.scanning.warn.message": "true",
39
+ "last_opened_file_path": "C:/GitHubWS/nano_dev_utils/tests",
40
+ "settings.editor.selected.configurable": "com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable"
41
+ }
42
+ }]]></component>
43
+ <component name="RecentsManager">
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" />
51
+ <recent name="C:\GitHubWS\nano_dev_utils" />
52
+ </key>
53
+ </component>
54
+ <component name="RunManager" selected="Python tests.Python tests in tests">
55
+ <configuration name="test_timer" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
56
+ <module name="nano_dev_utils" />
57
+ <option name="ENV_FILES" value="" />
58
+ <option name="INTERPRETER_OPTIONS" value="" />
59
+ <option name="PARENT_ENVS" value="true" />
60
+ <envs>
61
+ <env name="PYTHONUNBUFFERED" value="1" />
62
+ </envs>
63
+ <option name="SDK_HOME" value="" />
64
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
65
+ <option name="IS_MODULE_SDK" value="true" />
66
+ <option name="ADD_CONTENT_ROOTS" value="true" />
67
+ <option name="ADD_SOURCE_ROOTS" value="true" />
68
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/tests/test_timer.py" />
69
+ <option name="PARAMETERS" value="" />
70
+ <option name="SHOW_COMMAND_LINE" value="false" />
71
+ <option name="EMULATE_TERMINAL" value="false" />
72
+ <option name="MODULE_MODE" value="false" />
73
+ <option name="REDIRECT_INPUT" value="false" />
74
+ <option name="INPUT_FILE" value="" />
75
+ <method v="2" />
76
+ </configuration>
77
+ <configuration name="Python tests in test_timer.py" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
78
+ <module name="nano_dev_utils" />
79
+ <option name="ENV_FILES" value="" />
80
+ <option name="INTERPRETER_OPTIONS" value="" />
81
+ <option name="PARENT_ENVS" value="true" />
82
+ <option name="SDK_HOME" value="" />
83
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
84
+ <option name="IS_MODULE_SDK" value="true" />
85
+ <option name="ADD_CONTENT_ROOTS" value="true" />
86
+ <option name="ADD_SOURCE_ROOTS" value="true" />
87
+ <option name="_new_additionalArguments" value="&quot;&quot;" />
88
+ <option name="_new_target" value="&quot;$PROJECT_DIR$/tests/test_timer.py&quot;" />
89
+ <option name="_new_targetType" value="&quot;PATH&quot;" />
90
+ <method v="2" />
91
+ </configuration>
92
+ <configuration name="Python tests in tests" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
93
+ <module name="nano_dev_utils" />
94
+ <option name="ENV_FILES" value="" />
95
+ <option name="INTERPRETER_OPTIONS" value="" />
96
+ <option name="PARENT_ENVS" value="true" />
97
+ <option name="SDK_HOME" value="" />
98
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
99
+ <option name="IS_MODULE_SDK" value="true" />
100
+ <option name="ADD_CONTENT_ROOTS" value="true" />
101
+ <option name="ADD_SOURCE_ROOTS" value="true" />
102
+ <option name="_new_additionalArguments" value="&quot;&quot;" />
103
+ <option name="_new_target" value="&quot;$PROJECT_DIR$/tests&quot;" />
104
+ <option name="_new_targetType" value="&quot;PATH&quot;" />
105
+ <method v="2" />
106
+ </configuration>
107
+ <recent_temporary>
108
+ <list>
109
+ <item itemvalue="Python tests.Python tests in tests" />
110
+ <item itemvalue="Python tests.Python tests in test_timer.py" />
111
+ <item itemvalue="Python tests.Python tests in tests" />
112
+ <item itemvalue="Python.test_timer" />
113
+ </list>
114
+ </recent_temporary>
115
+ </component>
116
+ <component name="SharedIndexes">
117
+ <attachedChunks>
118
+ <set>
119
+ <option value="bundled-python-sdk-5b207ade9991-746f403e7f0c-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-241.17890.14" />
120
+ </set>
121
+ </attachedChunks>
122
+ </component>
123
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
124
+ <component name="TaskManager">
125
+ <task active="true" id="Default" summary="Default task">
126
+ <changelist id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="" />
127
+ <created>1746126505743</created>
128
+ <option name="number" value="Default" />
129
+ <option name="presentableId" value="Default" />
130
+ <updated>1746126505743</updated>
131
+ </task>
132
+ <task id="LOCAL-00001" summary=".">
133
+ <option name="closed" value="true" />
134
+ <created>1746126585369</created>
135
+ <option name="number" value="00001" />
136
+ <option name="presentableId" value="LOCAL-00001" />
137
+ <option name="project" value="LOCAL" />
138
+ <updated>1746126585369</updated>
139
+ </task>
140
+ <task id="LOCAL-00002" summary="license relative path">
141
+ <option name="closed" value="true" />
142
+ <created>1746126934201</created>
143
+ <option name="number" value="00002" />
144
+ <option name="presentableId" value="LOCAL-00002" />
145
+ <option name="project" value="LOCAL" />
146
+ <updated>1746126934201</updated>
147
+ </task>
148
+ <task id="LOCAL-00003" summary="license file renamed">
149
+ <option name="closed" value="true" />
150
+ <created>1746127675699</created>
151
+ <option name="number" value="00003" />
152
+ <option name="presentableId" value="LOCAL-00003" />
153
+ <option name="project" value="LOCAL" />
154
+ <updated>1746127675699</updated>
155
+ </task>
156
+ <task id="LOCAL-00004" summary="adding license path">
157
+ <option name="closed" value="true" />
158
+ <created>1746127874421</created>
159
+ <option name="number" value="00004" />
160
+ <option name="presentableId" value="LOCAL-00004" />
161
+ <option name="project" value="LOCAL" />
162
+ <updated>1746127874421</updated>
163
+ </task>
164
+ <task id="LOCAL-00005" summary="adding license url">
165
+ <option name="closed" value="true" />
166
+ <created>1746128395309</created>
167
+ <option name="number" value="00005" />
168
+ <option name="presentableId" value="LOCAL-00005" />
169
+ <option name="project" value="LOCAL" />
170
+ <updated>1746128395310</updated>
171
+ </task>
172
+ <task id="LOCAL-00006" summary="+pre-commit config">
173
+ <option name="closed" value="true" />
174
+ <created>1746694280668</created>
175
+ <option name="number" value="00006" />
176
+ <option name="presentableId" value="LOCAL-00006" />
177
+ <option name="project" value="LOCAL" />
178
+ <updated>1746694280668</updated>
179
+ </task>
180
+ <task id="LOCAL-00007" summary="removed [tool.hatch.build]">
181
+ <option name="closed" value="true" />
182
+ <created>1747321637844</created>
183
+ <option name="number" value="00007" />
184
+ <option name="presentableId" value="LOCAL-00007" />
185
+ <option name="project" value="LOCAL" />
186
+ <updated>1747321637844</updated>
187
+ </task>
188
+ <task id="LOCAL-00008" summary="+iterations parameter">
189
+ <option name="closed" value="true" />
190
+ <created>1747660086270</created>
191
+ <option name="number" value="00008" />
192
+ <option name="presentableId" value="LOCAL-00008" />
193
+ <option name="project" value="LOCAL" />
194
+ <updated>1747660086270</updated>
195
+ </task>
196
+ <task id="LOCAL-00009" summary="minor update">
197
+ <option name="closed" value="true" />
198
+ <created>1747661192289</created>
199
+ <option name="number" value="00009" />
200
+ <option name="presentableId" value="LOCAL-00009" />
201
+ <option name="project" value="LOCAL" />
202
+ <updated>1747661192289</updated>
203
+ </task>
204
+ <task id="LOCAL-00010" summary="corrected return type">
205
+ <option name="closed" value="true" />
206
+ <created>1747665494128</created>
207
+ <option name="number" value="00010" />
208
+ <option name="presentableId" value="LOCAL-00010" />
209
+ <option name="project" value="LOCAL" />
210
+ <updated>1747665494128</updated>
211
+ </task>
212
+ <task id="LOCAL-00011" summary="corrected return types - complete">
213
+ <option name="closed" value="true" />
214
+ <created>1747666293914</created>
215
+ <option name="number" value="00011" />
216
+ <option name="presentableId" value="LOCAL-00011" />
217
+ <option name="project" value="LOCAL" />
218
+ <updated>1747666293914</updated>
219
+ </task>
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" />
285
+ <servers />
286
+ </component>
287
+ <component name="Vcs.Log.Tabs.Properties">
288
+ <option name="TAB_STATES">
289
+ <map>
290
+ <entry key="MAIN">
291
+ <value>
292
+ <State />
293
+ </value>
294
+ </entry>
295
+ </map>
296
+ </option>
297
+ </component>
298
+ <component name="VcsManagerConfiguration">
299
+ <MESSAGE value="." />
300
+ <MESSAGE value="license relative path" />
301
+ <MESSAGE value="license file renamed" />
302
+ <MESSAGE value="adding license path" />
303
+ <MESSAGE value="adding license url" />
304
+ <MESSAGE value="+pre-commit config" />
305
+ <MESSAGE value="removed [tool.hatch.build]" />
306
+ <MESSAGE value="+iterations parameter" />
307
+ <MESSAGE value="minor update" />
308
+ <MESSAGE value="corrected return type" />
309
+ <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" />
319
+ </component>
320
+ </project>
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nano_dev_utils
3
- Version: 0.5.7
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,21 +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`.
36
-
37
- * **`timeit(self, func: Callable[P, R]) -> Callable[P, R]`**:
38
- Decorator that times function execution with automatic unit scaling.
39
- * When the decorated function is called, this decorator records the start and end times,
40
- calculates the total execution time, prints the function name and execution
41
- time (optionally including arguments), and returns the result of the original function.
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`.
34
+
35
+ * **`timeit(
36
+ self,
37
+ iterations: int = 1,
38
+ timeout: float | None = None,
39
+ per_iteration: bool = False
40
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
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)
42
54
 
43
55
  #### Example Usage:
44
56
 
@@ -48,16 +60,22 @@ from nano_dev_utils.timers import Timer
48
60
 
49
61
  timer = Timer(precision=6, verbose=True)
50
62
 
51
-
52
- @timer.timeit
63
+ # Basic timing
64
+ @timer.timeit()
53
65
  def my_function(a, b=10):
54
- """A sample function."""
55
- time.sleep(0.1)
56
- return a + b
57
-
58
-
59
- result = my_function(5, b=20)
60
- 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
61
79
  ```
62
80
 
63
81
  ### `dynamic_importer.py`
@@ -6,21 +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`.
18
-
19
- * **`timeit(self, func: Callable[P, R]) -> Callable[P, R]`**:
20
- Decorator that times function execution with automatic unit scaling.
21
- * When the decorated function is called, this decorator records the start and end times,
22
- calculates the total execution time, prints the function name and execution
23
- time (optionally including arguments), and returns the result of the original function.
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`.
16
+
17
+ * **`timeit(
18
+ self,
19
+ iterations: int = 1,
20
+ timeout: float | None = None,
21
+ per_iteration: bool = False
22
+ ) -> Callable[[Callable[P, R]], Callable[P, R | None]]`**:
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)
24
36
 
25
37
  #### Example Usage:
26
38
 
@@ -30,16 +42,22 @@ from nano_dev_utils.timers import Timer
30
42
 
31
43
  timer = Timer(precision=6, verbose=True)
32
44
 
33
-
34
- @timer.timeit
45
+ # Basic timing
46
+ @timer.timeit()
35
47
  def my_function(a, b=10):
36
- """A sample function."""
37
- time.sleep(0.1)
38
- return a + b
39
-
40
-
41
- result = my_function(5, b=20)
42
- 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
43
61
  ```
44
62
 
45
63
  ### `dynamic_importer.py`
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "nano_dev_utils"
3
- version = "0.5.7"
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,155 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="AutoImportSettings">
4
- <option name="autoReloadType" value="SELECTIVE" />
5
- </component>
6
- <component name="ChangeListManager">
7
- <list default="true" id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="removed [tool.hatch.build]">
8
- <change beforePath="$PROJECT_DIR$/pyproject.toml" beforeDir="false" afterPath="$PROJECT_DIR$/pyproject.toml" afterDir="false" />
9
- </list>
10
- <option name="SHOW_DIALOG" value="false" />
11
- <option name="HIGHLIGHT_CONFLICTS" value="true" />
12
- <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
13
- <option name="LAST_RESOLUTION" value="IGNORE" />
14
- </component>
15
- <component name="Git.Settings">
16
- <option name="RECENT_BRANCH_BY_REPOSITORY">
17
- <map>
18
- <entry key="$PROJECT_DIR$" value="yd_pre-commit" />
19
- </map>
20
- </option>
21
- <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
22
- </component>
23
- <component name="ProjectColorInfo">{
24
- &quot;customColor&quot;: &quot;&quot;,
25
- &quot;associatedIndex&quot;: 5
26
- }</component>
27
- <component name="ProjectId" id="2wVV0HQbcggEgX5PEayC1Mcx9Gd" />
28
- <component name="ProjectViewState">
29
- <option name="hideEmptyMiddlePackages" value="true" />
30
- <option name="showLibraryContents" value="true" />
31
- <option name="showMembers" value="true" />
32
- </component>
33
- <component name="PropertiesComponent"><![CDATA[{
34
- "keyToString": {
35
- "Python tests.Python tests in tests.executor": "Run",
36
- "RunOnceActivity.ShowReadmeOnStart": "true",
37
- "git-widget-placeholder": "master",
38
- "ignore.virus.scanning.warn.message": "true",
39
- "last_opened_file_path": "C:/GitHubWS/nano_dev_utils",
40
- "settings.editor.selected.configurable": "com.jetbrains.python.configuration.PyActiveSdkModuleConfigurable"
41
- }
42
- }]]></component>
43
- <component name="RecentsManager">
44
- <key name="CopyFile.RECENT_KEYS">
45
- <recent name="C:\GitHubWS\nano_dev_utils" />
46
- </key>
47
- </component>
48
- <component name="RunManager">
49
- <configuration name="Python tests in tests" type="tests" factoryName="Autodetect" temporary="true" nameIsGenerated="true">
50
- <module name="nano_dev_utils" />
51
- <option name="ENV_FILES" value="" />
52
- <option name="INTERPRETER_OPTIONS" value="" />
53
- <option name="PARENT_ENVS" value="true" />
54
- <option name="SDK_HOME" value="" />
55
- <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/tests" />
56
- <option name="IS_MODULE_SDK" value="true" />
57
- <option name="ADD_CONTENT_ROOTS" value="true" />
58
- <option name="ADD_SOURCE_ROOTS" value="true" />
59
- <option name="_new_additionalArguments" value="&quot;&quot;" />
60
- <option name="_new_target" value="&quot;$PROJECT_DIR$/tests&quot;" />
61
- <option name="_new_targetType" value="&quot;PATH&quot;" />
62
- <method v="2" />
63
- </configuration>
64
- <recent_temporary>
65
- <list>
66
- <item itemvalue="Python tests.Python tests in tests" />
67
- </list>
68
- </recent_temporary>
69
- </component>
70
- <component name="SharedIndexes">
71
- <attachedChunks>
72
- <set>
73
- <option value="bundled-python-sdk-5b207ade9991-746f403e7f0c-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-241.17890.14" />
74
- </set>
75
- </attachedChunks>
76
- </component>
77
- <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
78
- <component name="TaskManager">
79
- <task active="true" id="Default" summary="Default task">
80
- <changelist id="1859e23b-7665-4b92-98cc-65e07a208923" name="Changes" comment="" />
81
- <created>1746126505743</created>
82
- <option name="number" value="Default" />
83
- <option name="presentableId" value="Default" />
84
- <updated>1746126505743</updated>
85
- </task>
86
- <task id="LOCAL-00001" summary=".">
87
- <option name="closed" value="true" />
88
- <created>1746126585369</created>
89
- <option name="number" value="00001" />
90
- <option name="presentableId" value="LOCAL-00001" />
91
- <option name="project" value="LOCAL" />
92
- <updated>1746126585369</updated>
93
- </task>
94
- <task id="LOCAL-00002" summary="license relative path">
95
- <option name="closed" value="true" />
96
- <created>1746126934201</created>
97
- <option name="number" value="00002" />
98
- <option name="presentableId" value="LOCAL-00002" />
99
- <option name="project" value="LOCAL" />
100
- <updated>1746126934201</updated>
101
- </task>
102
- <task id="LOCAL-00003" summary="license file renamed">
103
- <option name="closed" value="true" />
104
- <created>1746127675699</created>
105
- <option name="number" value="00003" />
106
- <option name="presentableId" value="LOCAL-00003" />
107
- <option name="project" value="LOCAL" />
108
- <updated>1746127675699</updated>
109
- </task>
110
- <task id="LOCAL-00004" summary="adding license path">
111
- <option name="closed" value="true" />
112
- <created>1746127874421</created>
113
- <option name="number" value="00004" />
114
- <option name="presentableId" value="LOCAL-00004" />
115
- <option name="project" value="LOCAL" />
116
- <updated>1746127874421</updated>
117
- </task>
118
- <task id="LOCAL-00005" summary="adding license url">
119
- <option name="closed" value="true" />
120
- <created>1746128395309</created>
121
- <option name="number" value="00005" />
122
- <option name="presentableId" value="LOCAL-00005" />
123
- <option name="project" value="LOCAL" />
124
- <updated>1746128395310</updated>
125
- </task>
126
- <task id="LOCAL-00006" summary="+pre-commit config">
127
- <option name="closed" value="true" />
128
- <created>1746694280668</created>
129
- <option name="number" value="00006" />
130
- <option name="presentableId" value="LOCAL-00006" />
131
- <option name="project" value="LOCAL" />
132
- <updated>1746694280668</updated>
133
- </task>
134
- <task id="LOCAL-00007" summary="removed [tool.hatch.build]">
135
- <option name="closed" value="true" />
136
- <created>1747321637844</created>
137
- <option name="number" value="00007" />
138
- <option name="presentableId" value="LOCAL-00007" />
139
- <option name="project" value="LOCAL" />
140
- <updated>1747321637844</updated>
141
- </task>
142
- <option name="localTasksCounter" value="8" />
143
- <servers />
144
- </component>
145
- <component name="VcsManagerConfiguration">
146
- <MESSAGE value="." />
147
- <MESSAGE value="license relative path" />
148
- <MESSAGE value="license file renamed" />
149
- <MESSAGE value="adding license path" />
150
- <MESSAGE value="adding license url" />
151
- <MESSAGE value="+pre-commit config" />
152
- <MESSAGE value="removed [tool.hatch.build]" />
153
- <option name="LAST_COMMIT_MESSAGE" value="removed [tool.hatch.build]" />
154
- </component>
155
- </project>
@@ -1,38 +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(self, func: Callable[P, R]) -> Callable[P, R]:
16
- """Decorator that times function execution with automatic unit scaling."""
17
-
18
- @wraps(func)
19
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
20
- start = time.perf_counter_ns()
21
- result = func(*args, **kwargs)
22
- elapsed = time.perf_counter_ns() - start
23
-
24
- value = elapsed
25
- unit = 'ns'
26
-
27
- for divisor, unit in self.units:
28
- if elapsed >= divisor or unit == 'ns':
29
- value = elapsed / divisor
30
- break
31
-
32
- extra_info = f'{args} {kwargs} ' if self.verbose else ''
33
- print(
34
- f'{func.__name__} {extra_info}took {value:.{self.precision}f} [{unit}]'
35
- )
36
- return result
37
-
38
- return wrapper
@@ -1,159 +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'
File without changes