Return elapsed time for executing code in the namespace of the caller. The supplied code string is compiled with the Python builtin ``compile``. The precision of the timing is 10 milli-seconds. If the code will execute fast on this timescale, it can be executed many times to get re
(code_str, times=1, label=None)
| 1364 | |
| 1365 | |
| 1366 | def measure(code_str, times=1, label=None): |
| 1367 | """ |
| 1368 | Return elapsed time for executing code in the namespace of the caller. |
| 1369 | |
| 1370 | The supplied code string is compiled with the Python builtin ``compile``. |
| 1371 | The precision of the timing is 10 milli-seconds. If the code will execute |
| 1372 | fast on this timescale, it can be executed many times to get reasonable |
| 1373 | timing accuracy. |
| 1374 | |
| 1375 | Parameters |
| 1376 | ---------- |
| 1377 | code_str : str |
| 1378 | The code to be timed. |
| 1379 | times : int, optional |
| 1380 | The number of times the code is executed. Default is 1. The code is |
| 1381 | only compiled once. |
| 1382 | label : str, optional |
| 1383 | A label to identify `code_str` with. This is passed into ``compile`` |
| 1384 | as the second argument (for run-time error messages). |
| 1385 | |
| 1386 | Returns |
| 1387 | ------- |
| 1388 | elapsed : float |
| 1389 | Total elapsed time in seconds for executing `code_str` `times` times. |
| 1390 | |
| 1391 | Examples |
| 1392 | -------- |
| 1393 | >>> times = 10 |
| 1394 | >>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)', times=times) |
| 1395 | >>> print("Time for a single execution : ", etime / times, "s") # doctest: +SKIP |
| 1396 | Time for a single execution : 0.005 s |
| 1397 | |
| 1398 | """ |
| 1399 | frame = sys._getframe(1) |
| 1400 | locs, globs = frame.f_locals, frame.f_globals |
| 1401 | |
| 1402 | code = compile(code_str, f'Test name: {label} ', 'exec') |
| 1403 | i = 0 |
| 1404 | elapsed = jiffies() |
| 1405 | while i < times: |
| 1406 | i += 1 |
| 1407 | exec(code, globs, locs) |
| 1408 | elapsed = jiffies() - elapsed |
| 1409 | return 0.01*elapsed |
| 1410 | |
| 1411 | |
| 1412 | def _assert_valid_refcount(op): |