Skip to content

Instantly share code, notes, and snippets.

@akochepasov
Created November 21, 2024 18:39
Show Gist options
  • Save akochepasov/6c877ee52c9dc209eea426c7acf3e811 to your computer and use it in GitHub Desktop.
Save akochepasov/6c877ee52c9dc209eea426c7acf3e811 to your computer and use it in GitHub Desktop.
Working with c++ std::chrono
#include <cstdlib>
#include <iostream>
#include <chrono>
using std::chrono::steady_clock;
using std::chrono::system_clock;
constexpr inline std::chrono::seconds timeout1 =
std::chrono::seconds(60 * 60);
constexpr inline std::chrono::minutes timeout2 =
std::chrono::minutes(5);
std::string to_string(const std::time_t& timepoint) {
struct tm tbuf;
constexpr size_t bufSz = 128;
std::string strbuf(bufSz, 0);
std::strftime(&strbuf[0], bufSz, "%Y-%m-%d-%H:%M:%S", ::gmtime_r(&timepoint, &tbuf));
return strbuf;
}
std::string to_string(const steady_clock::time_point& timepoint) {
auto clock_diff = timepoint - steady_clock::now();
time_t time_ = system_clock::to_time_t(system_clock::now() + clock_diff);
return to_string(time_);
}
int main() {
using clock = std::chrono::steady_clock;
clock::duration d_timeout1 = timeout1;
clock::duration d_timeout2 = timeout2;
auto clock_now = clock::now();
auto next_timepoint1 = clock::now() + d_timeout1;
auto next_timepoint2 = clock::now() + d_timeout2;
std::cout << to_string(clock_now) << std::endl;
std::cout << to_string(next_timepoint1) << std::endl;
std::cout << to_string(next_timepoint2) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment