user1950349
user1950349

Reputation: 5146

Get current timestamp in microseconds since epoch?

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.

Upvotes: 14

Views: 28705

Answers (2)

Lorien Brune
Lorien Brune

Reputation: 881

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();

Upvotes: 15

Howard Hinnant
Howard Hinnant

Reputation: 218700

The epochs of the chrono clocks are unspecified. But practically you can think of the chrono clocks this way:

  1. 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.

  2. 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.

  3. 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());

Upvotes: 24

Related Questions