让我通过这个测试程序问我的问题:
#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;
}
我的机器上的输出:
分辨率(纳米)= 100
std :: cout需要多少纳秒?
std :: cout需要1000200纳秒
作为结果,我收到1000200
或1000300
或1000400
或1000500
或1000600
或2000600
(= 1或2微秒)。显然,std::chrono
的分辨率是not 100纳秒或我测量std::cout
的时间的方法是错误的。 (为什么我永远都不会收到1到2微秒之间的信息,例如1500000
?]
我需要使用C ++的高分辨率计时器。操作系统本身提供了高分辨率计时器,因为我可以在同一台计算机上使用C#Stopwatch
类以微秒级的精度进行测量。因此,我只需要正确使用操作系统具有的高分辨率计时器即可!
如何修复程序以产生预期的结果?
我猜您正在使用Visual Studio2012。如果没有,请忽略此答案。 Visual Studio 2012 typedef
的high_resolution_clock
至system_clock
。可悲的是,这意味着它的精度很差(大约1毫秒)。我写了一个更好的高分辨率时钟,在Visual Studio 2012中使用QueryPerformanceCounter
...
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));
}
((我遗漏了一个断言和#ifs来查看上面的代码是否正在Visual Studio 2012上对其进行编译。)
您可以在任何地方以与标准时钟相同的方式使用此时钟。
时钟的分辨率不一定与可以由时钟使用的数据类型表示的最小持续时间相同。在这种情况下,您的实现使用的数据类型可以表示持续时间仅为100纳秒,但是底层时钟实际上没有这样的分辨率。
Visual Studio high_resolution_clock
的低分辨率多年来一直是一个问题。 Microsoft的C ++标准库维护者Stephan T. Lavavej has indicated,此问题已通过使用QueryPerformanceCounter()
在VS2015中修复。
也许实现未实现更高分辨率的计时器?
似乎您正在使用Windows(提到C#),因此,如果您使用计时器而您确实在使用Windows,则可以使用QueryPerformanceFrequency和QueryPerformanceCounter。