mmengine/tests/test_utils/test_timer.py

52 lines
1.6 KiB
Python
Raw Normal View History

2022-08-22 11:51:56 +08:00
# Copyright (c) OpenMMLab. All rights reserved.
import platform
2022-08-22 11:51:56 +08:00
import time
import pytest
2022-08-23 16:56:47 +08:00
import mmengine
2022-08-22 11:51:56 +08:00
@pytest.mark.skipif(
platform.system() != 'Linux', reason='Only test `Timer` in linux!')
2022-08-22 11:51:56 +08:00
def test_timer_init():
2022-08-23 16:56:47 +08:00
timer = mmengine.Timer(start=False)
2022-08-22 11:51:56 +08:00
assert not timer.is_running
timer.start()
assert timer.is_running
2022-08-23 16:56:47 +08:00
timer = mmengine.Timer()
2022-08-22 11:51:56 +08:00
assert timer.is_running
@pytest.mark.skipif(
platform.system() != 'Linux', reason='Only test `Timer` in linux!')
2022-08-22 11:51:56 +08:00
def test_timer_run():
2022-08-23 16:56:47 +08:00
timer = mmengine.Timer()
2022-08-22 11:51:56 +08:00
time.sleep(1)
2022-09-13 11:46:21 +08:00
# In Windows, the error could be larger than 20ms. More details in
# https://stackoverflow.com/questions/11657734/sleep-for-exact-time-in-python. # noqa: E501
assert abs(timer.since_start() - 1) < 3e-2
2022-08-22 11:51:56 +08:00
time.sleep(1)
2022-09-13 11:46:21 +08:00
assert abs(timer.since_last_check() - 1) < 3e-2
assert abs(timer.since_start() - 2) < 3e-2
2022-08-23 16:56:47 +08:00
timer = mmengine.Timer(False)
with pytest.raises(mmengine.TimerError):
2022-08-22 11:51:56 +08:00
timer.since_start()
2022-08-23 16:56:47 +08:00
with pytest.raises(mmengine.TimerError):
2022-08-22 11:51:56 +08:00
timer.since_last_check()
@pytest.mark.skipif(
platform.system() != 'Linux', reason='Only test `Timer` in linux!')
2022-08-22 11:51:56 +08:00
def test_timer_context(capsys):
2022-08-23 16:56:47 +08:00
with mmengine.Timer():
2022-08-22 11:51:56 +08:00
time.sleep(1)
out, _ = capsys.readouterr()
2022-09-13 11:46:21 +08:00
# In Windows, the error could be larger than 20ms. More details in
# https://stackoverflow.com/questions/11657734/sleep-for-exact-time-in-python. # noqa: E501
assert abs(float(out) - 1) < 3e-2
2022-08-23 16:56:47 +08:00
with mmengine.Timer(print_tmpl='time: {:.1f}s'):
2022-08-22 11:51:56 +08:00
time.sleep(1)
out, _ = capsys.readouterr()
assert out == 'time: 1.0s\n'