Measurement with boost::posix_time::microsec_clock has error more than ten microseconds?

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

I have the following code:

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; 

Result of this code is

Duration by Boost posix: 0 Processing time is 24 microsec 

Why there is such a big divergence? Boost sucks as much as it should measure microseconds but it measures microseconds with tenth of microseconds error???

回答1:

Posix time: microsec_clock:

Get the UTC time using a sub second resolution clock. On Unix systems this is implemented using GetTimeOfDay. On most Win32 platforms it is implemented using ftime. Win32 systems often do not achieve microsecond resolution via this API. If higher resolution is critical to your application test your platform to see the achieved resolution.

ftime simply does not provide microsecond resolution. The argument may contain the word microsecond but the implementation does not provide any accuracy in that range. It's granularity is in the ms regime.

You'd get something different than ZERO when you operation needs more time, say more than at least 20ms.

Edit: Note: In the long run the microsec_clock implementation for Windows should use the GetSystemTimePreciseAsFileTime function when possible (min. req. Windows 8 desktop, Windows Server 2012 desktop) to achieve microsecond resolution.



回答2:

Unfortunately current Boost implementation of boost::posix_time::microsec_clock doesn't uses QueryPerformanceCounter Win32 API, it uses GetSystemTimeAsFileTime instead which in its turn uses GetSystemTime. But system time resolution is milliseconds (or even worse).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!