I have a below code from which we are trying to get current timestamp in microseconds since epoch time but we are using steady_clock
.
inline uint64_t get_timestamp()
{
std::chrono::time_point<std::chrono::steady_clock> ts = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(ts.time_since_epoch()).count();
}
Is this the right way to do that since as per my understanding steady_clock
is used to measure the passage of time not to get the current time of day? Or should I use system_clock
for this like as shown below:
inline uint64_t get_timestamp()
{
std::chrono::time_point<std::chrono::system_clock> ts = std::chrono::system_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(ts.time_since_epoch()).count();
}
I need to use std::chrono
package only since that's what all our code is using.
Convert from epoch to human-readable date String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds.
The number of milliseconds since the "Unix epoch" 1970-01-01T00:00:00Z (UTC). This value is independent of the time zone. This value is at most 8,640,000,000,000,000ms (100,000,000 days) from the Unix epoch. In other words: millisecondsSinceEpoch.
The epochs of the chrono clocks are unspecified. But practically you can think of the chrono clocks this way:
The epoch of steady_clock
is the time your application launched plus a signed random offset. I.e. you can't depend upon the epoch being the same across application launches. But the epoch will remain stable while an application is running.
The epoch of system_clock
is time since New Years 1970, not counting leap seconds, in the UTC timezone. Different implementations implement this with varying precision: libc++ counts microseconds, VS counts 1/10 of microseconds, and gcc counts nanoseconds.
high_resolution_clock
is sometimes a type alias for steady_clock
and sometimes a type alias for system_clock
.
For a time stamp in microseconds I recommend first defining this type alias:
using time_stamp = std::chrono::time_point<std::chrono::system_clock,
std::chrono::microseconds>;
Store that, instead of uint64_t
. The type safety of this type will save you countless run time errors. You'll discover your errors at compile time instead.
You can get the current time_stamp
with:
using namespace std::chrono;
time_stamp ts = time_point_cast<microseconds>(system_clock::now());
Another possibility for people who couldn't get other solutions to work:
uint64_t microseconds_since_epoch = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With