Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How can we get a millisecond timestamp in linux?

How to convert std::chrono::monotonic_clock::now() to milliseconds and cast it to long?

using steady_clock or high_resolution_clock from chrono is also same. I have seen into std::chrono::duration_cast<std::chrono::milliseconds> but I only want the current timestamp and not any duration gaps.

like image 823
King Avatar asked Jan 25 '26 20:01

King


1 Answers

The current timestamp is defined with respect to some point in time (hence it is a duration). For instance, it is "typical" to get a timestamp with respect to the beginning of the Epoch (January 1st 1970, in Unix). You can do that by using time_since_epoch():

namespace chr = std::chrono;

chr::time_point<chr::steady_clock> tp = chr::steady_clock::now();
std::cout << "hours since epoch: "
          << chr::duration_cast<chr::hours>(tp.time_since_epoch()).count()
          << '\n';

To get the value in milliseconds you would need to cast it to std::chrono::milliseconds, instead.

like image 125
betabandido Avatar answered Jan 28 '26 12:01

betabandido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!