Skip to content

Commit

Permalink
cache time (qicosmos#367)
Browse files Browse the repository at this point in the history
  • Loading branch information
qicosmos authored Jul 13, 2023
1 parent 019296a commit d4dbaf4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
26 changes: 20 additions & 6 deletions include/cinatra/time_util.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::chrono::seconds>(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 <size_t N>
Expand Down
4 changes: 4 additions & 0 deletions tests/test_time_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit d4dbaf4

Please sign in to comment.