log, timer: improve BCLog::LogMsg()

- make timer code more homogeneous
- replace division with multiplication
- log if the time type is unexpected
This commit is contained in:
Jon Atack 2021-09-06 21:01:57 +02:00
parent 8d2f847ed9
commit 498b323425
No known key found for this signature in database
GPG key ID: 4F5721B3D0E3921D
2 changed files with 14 additions and 17 deletions

View file

@ -60,21 +60,13 @@ public:
if (std::is_same<TimeType, std::chrono::microseconds>::value) { if (std::is_same<TimeType, std::chrono::microseconds>::value) {
return strprintf("%s: %s (%iμs)", m_prefix, msg, end_time.count()); return strprintf("%s: %s (%iμs)", m_prefix, msg, end_time.count());
} } else if (std::is_same<TimeType, std::chrono::milliseconds>::value) {
return strprintf("%s: %s (%.2fms)", m_prefix, msg, end_time.count() * 0.001);
std::string units;
float divisor = 1;
if (std::is_same<TimeType, std::chrono::milliseconds>::value) {
units = "ms";
divisor = 1000.;
} else if (std::is_same<TimeType, std::chrono::seconds>::value) { } else if (std::is_same<TimeType, std::chrono::seconds>::value) {
units = "s"; return strprintf("%s: %s (%.2fs)", m_prefix, msg, end_time.count() * 0.000001);
divisor = 1000. * 1000.; } else {
return "Error: unexpected time type";
} }
const float time_ms = end_time.count() / divisor;
return strprintf("%s: %s (%.2f%s)", m_prefix, msg, time_ms, units);
} }
private: private:

View file

@ -15,9 +15,9 @@ BOOST_FIXTURE_TEST_SUITE(logging_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(logging_timer) BOOST_AUTO_TEST_CASE(logging_timer)
{ {
SetMockTime(1); SetMockTime(1);
auto sec_timer = BCLog::Timer<std::chrono::seconds>("tests", "end_msg"); auto micro_timer = BCLog::Timer<std::chrono::microseconds>("tests", "end_msg");
SetMockTime(2); SetMockTime(2);
BOOST_CHECK_EQUAL(sec_timer.LogMsg("test secs"), "tests: test secs (1.00s)"); BOOST_CHECK_EQUAL(micro_timer.LogMsg("test micros"), "tests: test micros (1000000μs)");
SetMockTime(1); SetMockTime(1);
auto ms_timer = BCLog::Timer<std::chrono::milliseconds>("tests", "end_msg"); auto ms_timer = BCLog::Timer<std::chrono::milliseconds>("tests", "end_msg");
@ -25,9 +25,14 @@ BOOST_AUTO_TEST_CASE(logging_timer)
BOOST_CHECK_EQUAL(ms_timer.LogMsg("test ms"), "tests: test ms (1000.00ms)"); BOOST_CHECK_EQUAL(ms_timer.LogMsg("test ms"), "tests: test ms (1000.00ms)");
SetMockTime(1); SetMockTime(1);
auto micro_timer = BCLog::Timer<std::chrono::microseconds>("tests", "end_msg"); auto sec_timer = BCLog::Timer<std::chrono::seconds>("tests", "end_msg");
SetMockTime(2); SetMockTime(2);
BOOST_CHECK_EQUAL(micro_timer.LogMsg("test micros"), "tests: test micros (1000000μs)"); BOOST_CHECK_EQUAL(sec_timer.LogMsg("test secs"), "tests: test secs (1.00s)");
SetMockTime(1);
auto minute_timer = BCLog::Timer<std::chrono::minutes>("tests", "end_msg");
SetMockTime(2);
BOOST_CHECK_EQUAL(minute_timer.LogMsg("test minutes"), "Error: unexpected time type");
} }
BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()