Iyengar111 / NanoLog

Low Latency C++11 Logging Library
727 stars 186 forks source link

should use system_clock instead of high_resolution_clock for timestamp_now #11

Open BTNC opened 7 years ago

BTNC commented 7 years ago

Only system_clock's epoch is guaranteed to be January 1, 1970, while steady_clock's epoch maybe not. high_resolution_clock maybe a synonym for system_clock or steady_clock. So system_clock should be used to get time_since_epoch if the desired epoch is January 1, 1970.

Iyengar111 commented 7 years ago

Hi,

Can you give me a reference where it mentions steady_clock epoch is not Jan 1, 1970.

Thanks.

BTNC commented 7 years ago

Search steady_clock from google could result lots of discussions about system_clock, steady_clock, etc. Below are 2 of those references: cppreference,stackoverflow

sandym commented 7 years ago

With libc++, high_resolution_clock epoch is the last boot time.

ghost commented 7 years ago

Also affected on windows VS2015, I get time stamps as [1970-01-02 06:01:03.451556]. system_clock works as expected [2017-02-02 12:22:14.434341].

If high_resolution_clock is important for time stamps, may be offset can be used?

    uint64_t timestamp_now()
    {
        static auto hrc_offset = std::chrono::system_clock::now().time_since_epoch() - std::chrono::high_resolution_clock::now().time_since_epoch();
        return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch() + hrc_offset).count();
    }
alanthie commented 6 years ago
uint64_t timestamp_now()
{
  return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}

void format_timestamp(std::ostream & os, uint64_t timestamp)
{
  auto usecs = std::chrono::microseconds(timestamp);
  auto secs = std::chrono::duration_cast<std::chrono::seconds> (usecs);
  usecs -= secs;
  std::time_t time_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::time_point{ secs });

  os << '[' << std::put_time(std::localtime(&time_t), "%Y-%m-%d %X");
  os << "." << usecs.count() << ']';
}

[2018-05-01 21:17:45.272498][INFO][20072][c:\work\nanolog\main.cpp:main:20] Sample NanoLog: 0 [2018-05-01 21:17:45.272508][INFO][20072][c:\work\nanolog\main.cpp:main:20] Sample NanoLog: 1 [2018-05-01 21:17:45.272513][INFO][20072][c:\work\nanolog\main.cpp:main:20] Sample NanoLog: 2 [2018-05-01 21:17:45.272517][INFO][20072][c:\work\nanolog\main.cpp:main:20] Sample NanoLog: 3 [2018-05-01 21:17:45.272522][INFO][20072][c:\work\nanolog\main.cpp:main:20] Sample NanoLog: 4