test_stopwatch: fix on mingw

There are some timing shenanigans with GCC's chrono that make this
unreliable. Add a start/stop and test for that to work around.

Signed-off-by: Rosen Penev <rosenp@gmail.com>
This commit is contained in:
Rosen Penev 2022-06-23 17:18:35 -07:00
parent a26e174b36
commit 68f42a5b90

View File

@ -5,31 +5,40 @@
TEST_CASE("stopwatch1", "[stopwatch]") TEST_CASE("stopwatch1", "[stopwatch]")
{ {
using std::chrono::milliseconds; using std::chrono::milliseconds;
using clock = std::chrono::steady_clock;
milliseconds wait_ms(250); milliseconds wait_ms(250);
milliseconds tolerance_ms(250); milliseconds tolerance_ms(250);
auto start = clock::now();
spdlog::stopwatch sw; spdlog::stopwatch sw;
std::this_thread::sleep_for(wait_ms); std::this_thread::sleep_for(wait_ms);
REQUIRE(sw.elapsed() >= wait_ms); auto stop = clock::now();
REQUIRE(sw.elapsed() <= wait_ms + tolerance_ms); auto diff_ms = std::chrono::duration_cast<milliseconds>(stop - start);
REQUIRE(sw.elapsed() >= diff_ms);
REQUIRE(sw.elapsed() <= diff_ms + tolerance_ms);
} }
TEST_CASE("stopwatch2", "[stopwatch]") TEST_CASE("stopwatch2", "[stopwatch]")
{ {
using spdlog::sinks::test_sink_st; using spdlog::sinks::test_sink_st;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using clock = std::chrono::steady_clock;
std::chrono::duration<double> wait_duration(0.250); clock::duration wait_duration(milliseconds(250));
std::chrono::duration<double> tolerance_duration(0.250); clock::duration tolerance_duration(milliseconds(250));
auto test_sink = std::make_shared<test_sink_st>(); auto test_sink = std::make_shared<test_sink_st>();
auto start = clock::now();
spdlog::stopwatch sw; spdlog::stopwatch sw;
spdlog::logger logger("test-stopwatch", test_sink); spdlog::logger logger("test-stopwatch", test_sink);
logger.set_pattern("%v"); logger.set_pattern("%v");
std::this_thread::sleep_for(wait_duration); std::this_thread::sleep_for(wait_duration);
auto stop = clock::now();
logger.info("{}", sw); logger.info("{}", sw);
auto val = std::stod(test_sink->lines()[0]); auto val = std::stod(test_sink->lines()[0]);
auto diff_duration = duration_cast<std::chrono::duration<double>>(stop - start);
REQUIRE(val >= wait_duration.count()); REQUIRE(val >= diff_duration.count());
REQUIRE(val <= (wait_duration + tolerance_duration).count()); REQUIRE(val <= (diff_duration + tolerance_duration).count());
} }