问题
My Code looks like:
// Next 2 lines should be at the same time
auto nowMonotonic = std::chrono::steady_clock::now();
auto nowSystem = std::chrono::system_clock::now();
// Do some calc with nowMonotonic and nowSystem
This can happen:
auto nowMonotonic = std::chrono::steady_clock::now();
// Some other thread/process interrupts this thread for an
// unspecific amount of time...
auto nowSystem = std::chrono::system_clock::now();
// Do some calc with nowMonotonic and nowSystem
I'm working on a (non-realtime) linux system. I'm doing some calculations based on the current steady_clock
and the current system_clock
. The result is better than less the jitter between the reading of the two clock is.
What is the best way to read the two clocks at (nearly) the same time?
Is there a special system call to do this? Is there a possibility to get the difference of these two clocks in a single system call?
回答1:
There is no way to do this perfectly, and there is not even a best way. And the way you have shown is one of the good ways. If you are willing to trade some run time you can gain some better accuracy in a statistical sense by calling now()
more than once on each clock and averaging the results.
For example:
std::pair<std::chrono::steady_clock::time_point,
std::chrono::system_clock::time_point>
combined_now()
{
using namespace std::chrono;
auto u0 = system_clock::now();
auto t0 = steady_clock::now();
auto t1 = steady_clock::now();
auto u1 = system_clock::now();
return {t0 + (t1-t0)/2, u0 + (u1-u0)/2};
}
This is not necessarily better than what you have. But it is another tool in the toolbox to be aware of. As always, use tests with your specific use case to decide what is best for you.
来源:https://stackoverflow.com/questions/48165154/get-steady-clock-and-system-clock-at-the-same-time