std::chrono::high_resolution_clock 的分辨率与测量值不符
Resolution of std::chrono::high_resolution_clock doesn't correspond to measurements
让我用这个测试程序来问我的问题:
#include <iostream>
#include <chrono>
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
int main(int argc, char* argv[])
{
std::cout
<< "Resolution (nano) = "
<< (double) std::chrono::high_resolution_clock::period::num /
std::chrono::high_resolution_clock::period::den *
1000 * 1000 * 1000
<< std::endl;
auto t1 = std::chrono::high_resolution_clock::now();
std::cout << "How many nanoseconds does std::cout take?" << std::endl;
auto t2 = std::chrono::high_resolution_clock::now();
auto diff = t2-t1;
nanoseconds ns = duration_cast<nanoseconds>(diff);
std::cout << "std::cout takes " << ns.count() << " nanoseconds"
<< std::endl;
return 0;
}
我的机器上的输出:
分辨率(nano) = 100
std::cout需要多少纳秒?
std::cout占用1000200纳秒
我收到1000200
或1000300
或1000400
或1000500
或1000600
或2000600
作为结果(= 1或2微秒)。显然,要么std::chrono
的分辨率是,而不是 100纳秒,要么是,我测量std::cout
的时间的方法是错误的。(为什么我从来没有收到1到2微秒之间的东西,例如1500000
?)
我需要一个高分辨率的定时器在c++。操作系统本身提供了一个高分辨率计时器,因为我可以在同一台机器上使用c# Stopwatch
类以微秒级的精度进行测量。所以我只需要正确使用操作系统的高分辨率计时器!
我如何修正我的程序以产生预期的结果?
我猜你用的是Visual Studio 2012。如果不是,忽略这个答案。Visual Studio 2012 typedef
的high_resolution_clock
到system_clock
。可悲的是,这意味着它的精度很差(大约1毫秒)。我写了一个更好的高分辨率时钟,使用QueryPerformanceCounter
在Visual Studio 2012中使用…
HighResClock.h:
struct HighResClock
{
typedef long long rep;
typedef std::nano period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<HighResClock> time_point;
static const bool is_steady = true;
static time_point now();
};
HighResClock.cpp:
namespace
{
const long long g_Frequency = []() -> long long
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return frequency.QuadPart;
}();
}
HighResClock::time_point HighResClock::now()
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency));
}
(我省略了一个assert和#if来查看它是否在Visual Studio 2012上从上面的代码编译)
时钟的分辨率不一定与时钟使用的数据类型可以表示的最小持续时间相同。在这种情况下,您的实现使用的数据类型可以表示小到100纳秒的持续时间,但底层时钟实际上没有这样的分辨率。
Visual Studio的high_resolution_clock
的低分辨率已经是一个问题好几年了。微软的c++标准库维护者Stephan T. Lavavej表示,通过使用QueryPerformanceCounter()
, Visual Studio 2015已经修复了这个问题。
也许实现不实现更高分辨率的计时器?
似乎你正在使用Windows(你提到c#),所以如果你使用计时器,你确实使用Windows,你可以使用queryperformancfrequency和QueryPerformanceCounter。
- 在C++中测量postscript字体宽度
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 用时钟测量程序的运行时间
- 使用分辨率定理用Z3证明
- Alt+Enter 在 Win32 应用中,管理大小调整和分辨率
- Opencv 恢复到比我设置的更高的分辨率
- 用于测量微秒的QueryPerformanceCounter的奇怪行为
- 为什么根据测量位置测量经过的时间时会有很大的不同?
- 在Windows(C++)中使用USB相机拍摄高分辨率照片
- 为什么我的程序在输入某个形状的面积的测量值后没有结束?
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- 分别测量每个线程上花费的 CPU 时间(C++)
- 如何测量管道延迟?
- C/C++ 位数组分辨率转换算法
- Windows 和 Linux 之间的相对路径分辨率差异?
- 如何在C++中为高分辨率时钟声明变量?
- 测量时间以在 c++ 中生成更好的随机数
- OpenCL 内核计时测量 0 秒或导致 SIGABRT
- std::chrono::high_resolution_clock 的分辨率与测量值不符
- 测量' std::clock() '的分辨率