From fd56f7e646cfc065e8d72e93d1a40e67e1ae62f0 Mon Sep 17 00:00:00 2001 From: Kefu Chai Date: Wed, 13 Jan 2021 13:58:48 +0800 Subject: [PATCH] common/ceph_time: print {milli,nano}seconds as float this change fixes the regression introduced by 6e1d42ca004ae191c445dac41606142c376124b1 add unit test for verifying 'operator<<' as well. Signed-off-by: Kefu Chai --- src/common/ceph_time.cc | 3 ++- src/test/common/test_time.cc | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/common/ceph_time.cc b/src/common/ceph_time.cc index 603165efb43c5..69b3cdde6e87d 100644 --- a/src/common/ceph_time.cc +++ b/src/common/ceph_time.cc @@ -324,7 +324,8 @@ std::chrono::seconds parse_timespan(const std::string& s) namespace std { template ostream& operator<<(ostream& m, const chrono::duration& t) { - if constexpr (chrono::treat_as_floating_point_v) { + if constexpr (chrono::treat_as_floating_point_v || + Period::den > 1) { using seconds_t = chrono::duration; ::fmt::print(m, "{:.9}", chrono::duration_cast(t)); } else { diff --git a/src/test/common/test_time.cc b/src/test/common/test_time.cc index 347916114bf39..3054aa50ef7ac 100644 --- a/src/test/common/test_time.cc +++ b/src/test/common/test_time.cc @@ -192,3 +192,43 @@ TEST(TimePoints, stringify) { ASSERT_TRUE(s[26] == '-' || s[26] == '+'); ASSERT_EQ(s.substr(0, 9), "2019-04-2"); } + +namespace { + template + std::string to_string(const chrono::duration& t) + { + std::ostringstream ss; + ss << t; + return ss.str(); + } + + void float_format_eq(string_view lhs, + string_view rhs, + unsigned precision) + { + const float TOLERANCE = 10.0F / pow(10.0F, static_cast(precision)); + ASSERT_FALSE(lhs.empty()); + ASSERT_EQ(lhs.back(), 's'); + float lhs_v = std::stof(string{lhs, 0, lhs.find('s')}); + ASSERT_NE(lhs.npos, lhs.find('.')); + ASSERT_EQ(precision, lhs.find('s') - lhs.find('.') - 1); + + ASSERT_FALSE(rhs.empty()); + ASSERT_EQ(rhs.back(), 's'); + float rhs_v = std::stof(string{rhs, 0, rhs.find('s')}); + EXPECT_NEAR(lhs_v, rhs_v, TOLERANCE); + ASSERT_NE(rhs.npos, rhs.find('.')); + EXPECT_EQ(precision, rhs.find('s') - rhs.find('.') - 1); + } +} + +TEST(TimeDurations, print) { + float_format_eq("0.123456700s", + to_string(std::chrono::duration_cast(0.1234567s)), + 9); + float_format_eq("-0.123456700s", + to_string(std::chrono::duration_cast(-0.1234567s)), + 9); + EXPECT_EQ("42s", to_string(42s)); + float_format_eq("0.123000000s", to_string(123ms), 9); +} -- 2.39.5