2023-09-16 00:25:39 +05:30
|
|
|
import time
|
|
|
|
from functools import partial
|
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
|
|
|
from datahub.utilities.perf_timer import PerfTimer
|
|
|
|
|
2023-12-04 20:00:11 -05:00
|
|
|
approx = partial(pytest.approx, rel=2e-2)
|
2023-09-16 00:25:39 +05:30
|
|
|
|
|
|
|
|
2024-10-31 16:27:45 -07:00
|
|
|
def test_perf_timer_simple() -> None:
|
2023-09-16 00:25:39 +05:30
|
|
|
with PerfTimer() as timer:
|
2024-10-16 19:18:32 -07:00
|
|
|
time.sleep(0.4)
|
|
|
|
assert approx(timer.elapsed_seconds()) == 0.4
|
2023-09-16 00:25:39 +05:30
|
|
|
|
2024-10-16 19:18:32 -07:00
|
|
|
assert approx(timer.elapsed_seconds()) == 0.4
|
2023-09-16 00:25:39 +05:30
|
|
|
|
|
|
|
|
2024-10-31 16:27:45 -07:00
|
|
|
def test_perf_timer_paused_timer() -> None:
|
2023-09-16 00:25:39 +05:30
|
|
|
with PerfTimer() as current_timer:
|
2024-10-16 19:18:32 -07:00
|
|
|
time.sleep(0.5)
|
|
|
|
assert approx(current_timer.elapsed_seconds()) == 0.5
|
2023-09-16 00:25:39 +05:30
|
|
|
with current_timer.pause():
|
2024-10-16 19:18:32 -07:00
|
|
|
time.sleep(0.3)
|
|
|
|
assert approx(current_timer.elapsed_seconds()) == 0.5
|
|
|
|
assert approx(current_timer.elapsed_seconds()) == 0.5
|
|
|
|
time.sleep(0.2)
|
2023-09-16 00:25:39 +05:30
|
|
|
|
2024-10-16 19:18:32 -07:00
|
|
|
assert approx(current_timer.elapsed_seconds()) == 0.7
|
2023-09-16 00:25:39 +05:30
|
|
|
|
|
|
|
|
2024-10-31 16:27:45 -07:00
|
|
|
def test_generator_with_paused_timer() -> None:
|
2024-10-16 19:18:32 -07:00
|
|
|
n = 4
|
|
|
|
|
2023-09-16 00:25:39 +05:30
|
|
|
def generator_function():
|
|
|
|
with PerfTimer() as inner_timer:
|
|
|
|
time.sleep(1)
|
2024-10-16 19:18:32 -07:00
|
|
|
for i in range(n):
|
2023-09-16 00:25:39 +05:30
|
|
|
time.sleep(0.2)
|
|
|
|
with inner_timer.pause():
|
|
|
|
time.sleep(0.2)
|
|
|
|
yield i
|
2024-10-16 19:18:32 -07:00
|
|
|
assert approx(inner_timer.elapsed_seconds()) == 1 + 0.2 * n
|
2023-09-16 00:25:39 +05:30
|
|
|
|
|
|
|
with PerfTimer() as outer_timer:
|
|
|
|
seq = generator_function()
|
|
|
|
list([i for i in seq])
|
2024-10-16 19:18:32 -07:00
|
|
|
assert approx(outer_timer.elapsed_seconds()) == 1 + 0.2 * n + 0.2 * n
|
2024-10-31 16:27:45 -07:00
|
|
|
|
|
|
|
|
|
|
|
def test_perf_timer_reuse() -> None:
|
|
|
|
timer = PerfTimer()
|
|
|
|
|
|
|
|
with timer:
|
|
|
|
time.sleep(0.2)
|
|
|
|
|
|
|
|
with timer:
|
|
|
|
time.sleep(0.3)
|
|
|
|
|
|
|
|
assert approx(timer.elapsed_seconds()) == 0.5
|