Say we have a very basic code to check an elapsed interval
#include <iostream>
#include <chrono>
int main()
{
auto start = std::chrono::steady_clock::now();
// some work
auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> diff = end-start;
std::cout << "The interval is " << diff.count() << "\n";
}
Does each call to std::chrono::steady_clock::now()
block other threads ? Is it considered lock free, or even wait free ? Does a call to std::chrono::steady_clock::now()
ever starve or block any other thread ?
I am most interested in what the specification guarantees for std::chrono::steady_clock::now()
. If it does not guarantee it to be wait free, is there any way to get a tick of a monotonic clock on MSVC/gcc/clang that is guaranteed to be wait free ?
The C++ standard is silent on this issue.
Rationale: Every OS has some way of getting monotonic time. Down at the hardware level this is a counter per clock cycle. At the OS level this may or may not translate to scaling to some convenient units such as nanoseconds.
The problem <chrono>
solves is that the OS API for getting this measure of time is different as one moves across OS's, and sometimes even as one moves from one version to the next. <chrono>
makes the underlying API uniform for the C++ programmer. Nothing more, nothing less.
So to answer this question, you really have to drop down to the OS level timing API.