Implementation of chrono library

Viewed 869

In C++, we can use chrono library to handle the time. And I think it's asynchronous with CPU clock. I mean,chrono::seconds(1) is real 1 second and not relative with how many instruction was executed during this duration. Am I right?

If I'm right, how it works at low level? Is there any timer hardware works asynchronously with CPU clock in general modern computer architecture?

1 Answers

Your typical modern computer has two ways to tell time, and these two ways help each other under the hood.

  1. There is typically a Time Stamp Counter which is nothing but a special register that gets incremented with each clock cycle. The computer also knows its own cycle time, and so that count of cycles can be converted into a physical time duration such as nanoseconds. This is ultimately what is used when an OS supplies a "real time clock", known in C++11 and later as std::chrono::steady_clock.

  2. Additionally modern computers understand and participate in a Network Time Protocol. This is essentially an organized way for one computer to ask another computer what the current UTC time is. A computer can use this to find out the current time, and then use its local Time Stamp Counter to translate that into a UTC time at a later time. A computer may use the NTP several times a day to keep its local time keeping accurate. In C++11 and later this is accessed via std::chrono::system_clock.

Decades ago, personal computers did not participate in NTP, and instead asked the human who booted up the computer the current time and date, and then used its onboard TSC to keep local time.

Update

Please read Peter Cordes comments below for details that I glossed over.

Related