c++c++11c++-chrono

Different behaviour of high_resolution_clock on windows and linux


The high_resolution_clock::now().time_since_epoch() returns significantly different results on Windows and Linux. On Linux it returns the duration from 1.1.1970 to now. On Windows it returns the duration of 21 days only.

I was running the following simple code on Windows

#include<iostream>
#include<chrono>

int main(int argc, char** argv) 
{
  std::cout << std::chrono::high_resolution_clock::now().time_since_epoch().count() << std::endl;
  return 0;
}

and the result was 1819149491213100 ns, which was just 21 days. I then ran the code on Linux and it printed the time since 1.1.1970 (which is what I expected). I also tired the steady_clock, and the results were similar. But when I try system_clock, the behaviour on both OSs turn out to be consistent.

Why does this code behave so differently on different OSs? The results indicate that Windows and Linux use different epoch times, but where does this 21 days come from? Does this various behaviour indicate that we should not use high_resolution_clock for timestamps, but for computing durations only?

ps: I ran the code on Visual Studio 2022.


update:

After rebooting my PC, the epoch time of the high_resolusion_clock is reset!

Here the doc of steady_clock from cppreference:

steady_clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.

In my case, I assume the high_resolution_clock is just an alias of steady_clock.


Solution

  • From cppreference:

    Class std::chrono::high_resolution_clock represents the clock with the smallest tick period provided by the implementation. It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.

    And std::system_clock, had unspecified epoch before C++20. Since C++20 it is

    [...] Unix Time (i.e., time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, not counting leap seconds).

    On the other hand std::steady_clock has unspecified epoch as its main purpose is to measure time differences:

    This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.

    A "third independent clock" could have a totally different epoch.