How to convert std::chrono::time_point to microseconds since epoch
If you have a std::chrono::time_point such as
timepoint_example.cpp
std::chrono::time_point<std::chrono::system_clock> timepoint = std::chrono::system_clock::now();You can convert it to microseconds since epoch by first casting it to a chrono::duration using
timepoint_time_since_epoch.cpp
timepoint.time_since_epoch(); // Returns a duration
and then using std::chrono::duration_cast<std::chrono::milliseconds>(...).count() to convert it to microseconds since epoch and getting the number of intervals (= microseconds) in between epoch and the time point.
example.cpp
std::chrono::duration_cast<std::chrono::microseconds>(timepoint.time_since_epoch()).count()Full example:
chrono_to_microseconds.cpp
#include <chrono>
#include <iostream>
int main()
{
auto timepoint = std::chrono::system_clock::now();
std::cout << "Microseconds since epoch: " <<
std::chrono::duration_cast<std::chrono::microseconds>(timepoint.time_since_epoch()).count() << std::endl;
}This prints, for example:
chrono_microseconds_example_output.txt
Microseconds since epoch: 1690755479946000Here’s a simple snippet to convert std::chrono::time_point to microseconds:
timepoint_to_us.cpp
#include <chrono>
#include <cstdint>
int64_t to_microseconds_since_epoch(std::chrono::system_clock::time_point tp) {
return std::chrono::duration_cast<std::chrono::microseconds>(tp.time_since_epoch()).count();
}Usage example:
timepoint_usage.cpp
auto now = std::chrono::system_clock::now();
int64_t us = to_microseconds_since_epoch(now);Check out similar posts by category:
C/C++
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow