我有以下代码:
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 很糟糕,因为它应该测量微秒,但它测量微秒的误差只有十分之一微秒???
Posix 时间:微秒时钟:
使用亚秒分辨率时钟获取 UTC 时间。在 Unix 系统上,这是使用 GetTimeOfDay 实现的。在大多数 Win32 平台上,它是使用 ftime 实现的。 Win32 系统通常无法通过此 API 实现微秒分辨率。如果更高的分辨率对您的应用程序至关重要,请测试您的平台以查看所达到的分辨率。
ftime
根本不提供微秒分辨率。参数可能包含单词microsecond
但该实现并没有提供该范围内的任何准确性。它的粒度是在 ms 范围内。
当您的操作需要更多时间(例如至少超过 20 毫秒)时,您会得到与 ZERO 不同的结果。
Edit:注:从长远来看microsec_clock
Windows 的实现should使用GetSystemTimePreciseAsFileTime 函数尽可能(至少要求 Windows 8 桌面、Windows Server 2012 桌面)实现微秒分辨率。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)