我有以下代码:
long long unsigned int GetCurrentTimestamp()
{
LARGE_INTEGER res;
QueryPerformanceCounter(&res);
return res.QuadPart;
}
long long unsigned int initalizeFrequency()
{
LARGE_INTEGER res;
QueryPerformanceFrequency(&res);
return res.QuadPart;
}
//start time stamp
boost::posix_time::ptime startTime = boost::posix_time::microsec_clock::local_time();
long long unsigned int start = GetCurrentTimestamp();
// ....
// execution that should be measured
// ....
long long unsigned int end = GetCurrentTimestamp();
boost::posix_time::ptime endTime = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration duration = endTime - startTime;
std::cout << "Duration by Boost posix: " << duration.total_microseconds() <<std::endl;
std::cout << "Processing time is " << ((end - start) * 1000000 / initalizeFrequency())
<< " microsec "<< std::endl;
这段代码的结果是
Duration by Boost posix: 0
Processing time is 24 microsec
为什么会有这么大的分歧? Boost 很糟糕,它应该测量微秒,但它测量微秒时有十分之一微秒的误差???
最佳答案
正时:microsec_clock:
使用亚秒分辨率时钟获取 UTC 时间。在 Unix 系统上,这是使用 GetTimeOfDay 实现的。在大多数 Win32 平台上,它是使用 ftime 实现的。 Win32 系统通常无法通过此 API 实现微秒分辨率。如果更高的分辨率对您的应用至关重要,请测试您的平台以查看实现的分辨率。
ftime
根本不提供微秒分辨率。参数可能包含单词 microsecond
但实现不提供该范围内的任何精度。它的粒度在 ms 范围内。
当您的操作需要更多时间时,您会得到与零不同的东西,比方说至少超过 20 毫秒。
编辑:注意:从长远来看,Windows 的microsec_clock
实现应该使用GetSystemTimePreciseAsFileTime function尽可能(最低要求 Windows 8 桌面、Windows Server 2012 桌面)以实现微秒分辨率。
关于c++ - 使用 boost::posix_time::microsec_clock 的测量误差超过十微秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12972221/