From 583ca02ef923e723c8cccd9c55fb826262f8507f Mon Sep 17 00:00:00 2001 From: Sergey Kovalevich Date: Tue, 22 Dec 2015 00:20:15 +0300 Subject: [PATCH 1/2] Added CLOCK_MONOTONIC trick --- include/spdlog/details/os.h | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index ab569caa..e938e6cf 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -35,6 +35,20 @@ namespace details namespace os { +#if defined __linux__ && defined SPDLOG_CLOCK_MONOTONIC +inline uint64_t clock_offset() +{ + timespec ts_realtime; + ::clock_gettime(CLOCK_REALTIME, &ts_realtime); + timespec ts_monotonic; + ::clock_gettime(CLOCK_MONOTONIC, &ts_monotonic); + + const uint64_t realtime = ts_realtime.tv_sec * 1000000000 + ts_realtime.tv_nsec; + const uint64_t monotonic = ts_monotonic.tv_sec * 1000000000 + ts_monotonic.tv_nsec; + return realtime - monotonic; +} +#endif + inline spdlog::log_clock::time_point now() { @@ -45,6 +59,14 @@ inline spdlog::log_clock::time_point now() std::chrono::duration_cast( std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec))); +#elif defined __linux__ && defined SPDLOG_CLOCK_MONOTONIC + static const auto offset = std::chrono::nanoseconds(clock_offset()); + + timespec ts; + ::clock_gettime(CLOCK_MONOTONIC, &ts); + return std::chrono::time_point( + std::chrono::duration_cast( + offset + std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec))); #else return log_clock::now(); #endif @@ -151,7 +173,7 @@ inline bool file_exists(const std::string& filename) #elif __linux__ struct stat buffer; return (stat (filename.c_str(), &buffer) == 0); -#else +#else auto *file = fopen(filename.c_str(), "r"); if (file != nullptr) { From 9e8c8c1113908b8e8d2af0ff1e6bcdbb3fb182a3 Mon Sep 17 00:00:00 2001 From: Sergey Kovalevich Date: Tue, 22 Dec 2015 07:21:43 +0300 Subject: [PATCH 2/2] added SPDLOG_CLOCK_MONOTONIC example entry in tweakme file --- include/spdlog/tweakme.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h index f1365147..56dbb563 100644 --- a/include/spdlog/tweakme.h +++ b/include/spdlog/tweakme.h @@ -17,6 +17,14 @@ /////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +// Under Linux, the much faster CLOCK_MONOTONIC clock can be used. +// This clock is more accurate than CLOCK_REALTIME_COARSE and faster than regular clock. +// Uncomment to use it instead of the regular clock. +// #define SPDLOG_CLOCK_MONOTONIC +/////////////////////////////////////////////////////////////////////////////// + + /////////////////////////////////////////////////////////////////////////////// // Uncomment if date/time logging is not needed. // This will prevent spdlog from quering the clock on each log call.