使用C ++ 11的可移植计时代码的正确方法 [英] Correct way of portably timing code using C++11

查看:97
本文介绍了使用C ++ 11的可移植计时代码的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为要求低延迟的程序的一部分编写一些时序代码.

I'm in the midst of writing some timing code for a part of a program that has a low latency requirement.

看看std :: chrono库中的可用内容,我发现编写可移植的计时代码有点困难.

Looking at whats available in the std::chrono library, I'm finding it a bit difficult to write timing code that is portable.

  1. std :: chrono :: high_resolution_clock
  2. std :: chrono :: steady_clock
  3. std :: chrono :: system_clock

system_clock没用,因为它不稳定,剩下的两个时钟有问题.

The system_clock is useless as it's not steady, the remaining two clocks are problematic.

high_resolution_clock不一定在所有平台上都稳定.

The high_resolution_clock isn't necessarily stable on all platforms.

steady_clock不一定支持精细的分辨率时间段(例如:纳秒)

The steady_clock does not necessarily support fine-grain resolution time periods (eg: nano seconds)

出于我的目的,保持时钟稳定是最重要的要求,我可以通过微秒级的粒度来解决问题.

For my purposes having a steady clock is the most important requirement and I can sort of get by with microsecond granularity.

我的问题是,是否想计时可以在不同硬件架构和操作系统上运行的代码-最佳选择是什么?

My question is if one wanted to time code that could be running on different h/w architectures and OSes - what would be the best option?

推荐答案

使用steady_clock.在所有实现中,其精度均为纳秒.您可以通过打印steady_clock::period::numsteady_clock::period::den来针对自己的平台进行检查.

Use steady_clock. On all implementations its precision is nanoseconds. You can check this yourself for your platform by printing out steady_clock::period::num and steady_clock::period::den.

现在,这并不意味着它将实际测量纳秒精度.但是平台会尽力而为.对我来说,连续两次调用steady_clock(启用了优化)将报告时间间隔为100ns.

Now that doesn't mean that it will actually measure nanosecond precision. But platforms do their best. For me, two consecutive calls to steady_clock (with optimizations enabled) will report times on the order of 100ns apart.

#include "chrono_io.h"
#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    using namespace date;
    auto t0 = steady_clock::now();
    auto t1 = steady_clock::now();
    auto t2 = steady_clock::now();
    auto t3 = steady_clock::now();
    std::cout << t1-t0 << '\n';
    std::cout << t2-t1 << '\n';
    std::cout << t3-t2 << '\n';
}

上面的示例使用了免费,开放源代码,仅标头的库仅用于格式化持续时间.您可以自己格式化(我很懒).对我来说,这只是输出:

The above example uses this free, open-source, header-only library only for convenience of formatting the duration. You can format things yourself (I'm lazy). For me this just output:

287ns
116ns
75ns

YMMV.

这篇关于使用C ++ 11的可移植计时代码的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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