From d4dbaf4e5b96becfc01feb7985952f2c1f60947a Mon Sep 17 00:00:00 2001 From: qicosmos Date: Thu, 13 Jul 2023 17:29:35 +0800 Subject: [PATCH] cache time (#367) --- include/cinatra/time_util.hpp | 26 ++++++++++++++++++++------ tests/test_time_util.cpp | 4 ++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/include/cinatra/time_util.hpp b/include/cinatra/time_util.hpp index e774e2b3..90501000 100644 --- a/include/cinatra/time_util.hpp +++ b/include/cinatra/time_util.hpp @@ -342,15 +342,29 @@ inline std::string_view get_local_time_str(char (&buf)[N], std::time_t t, // return {buf, n}; // } -inline std::string get_local_time_str(std::time_t t) { - char buf[32]; - auto s = get_local_time_str(buf, t, "%Y-%m-%d %H:%M:%S"); +inline std::string_view get_local_time_str( + std::chrono::system_clock::time_point t) { + static thread_local char buf[32]; + static thread_local std::chrono::seconds last_sec{}; + static thread_local size_t last_size{}; + + std::chrono::system_clock::duration d = t.time_since_epoch(); + std::chrono::seconds s = std::chrono::duration_cast(d); + if (last_sec == s) { + return {buf, last_size}; + } + + auto tm = std::chrono::system_clock::to_time_t(t); - return {s.data(), s.size()}; + auto str = get_local_time_str(buf, tm, "%Y-%m-%d %H:%M:%S"); + last_size = str.size(); + last_sec = s; + + return str; } -inline std::string get_local_time_str() { - return get_local_time_str(std::time(nullptr)); +inline std::string_view get_local_time_str() { + return get_local_time_str(std::chrono::system_clock::now()); } // template diff --git a/tests/test_time_util.cpp b/tests/test_time_util.cpp index 48d71f84..a293fea0 100644 --- a/tests/test_time_util.cpp +++ b/tests/test_time_util.cpp @@ -33,6 +33,9 @@ class ScopedTimer { }; void test_local_time_performance() { + auto local = cinatra::get_local_time_str(); + std::cout << local << "\n"; + int Count = 100000; std::string_view format = "%Y-%m-%d %H:%M:%S"; char buf[32]; @@ -76,6 +79,7 @@ void test_gmt_time_performance() { } TEST_CASE("test get time string") { + test_local_time_performance(); test_gmt_time_performance(); auto s = cinatra::get_local_time_str();