同时获取 stable_clock 和 system_clock [英] Get steady_clock and system_clock at the same time

查看:49
本文介绍了同时获取 stable_clock 和 system_clock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

// 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

这可能发生:

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

我正在开发一个(非实时)Linux 系统.我正在根据当前的 steady_clock 和当前的 system_clock 进行一些计算.结果好于两个时钟读取之间的抖动较小.

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.

在(几乎)同时读取两个时钟的最佳方式是什么?

是否有特殊的系统调用可以做到这一点?是否有可能在单个系统调用中获得这两个时钟的差异?

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?

推荐答案

没有办法完美地做到这一点,甚至没有最好的方法.你所展示的方式是很好的方式之一.如果您愿意牺牲一些运行时间,您可以通过在每个时钟上多次调用 now() 并平均结果来获得更好的统计意义上的准确性.

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.

例如:

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.

这篇关于同时获取 stable_clock 和 system_clock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆