使用boost :: posix_time :: microsec_clock进行的测量错误是否超过十微秒?

Nar*_*rek 5 c++ time winapi boost

我有以下代码:

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;
Run Code Online (Sandbox Code Playgroud)

该代码的结果是

Duration by Boost posix: 0
Processing time is 24 microsec
Run Code Online (Sandbox Code Playgroud)

为什么会有如此大的差异?Boost会吸尽它应测量的微秒,但它测量的微秒具有十分之一微秒的误差???

Arn*_*rno 4

Posix 时间:微秒时钟:

使用亚秒分辨率时钟获取 UTC 时间。在 Unix 系统上,这是使用 GetTimeOfDay 实现的。在大多数 Win32 平台上,它是使用 ftime 实现的。Win32 系统通常无法通过此 API 实现微秒分辨率。如果更高的分辨率对您的应用程序至关重要,请测试您的平台以查看所达到的分辨率。

ftime根本不提供微秒分辨率。参数可能包含该单词microsecond,但实现不提供该范围内的任何准确性。它的粒度是在 ms 范围内。

当您的操作需要更多时间(例如至少超过 20 毫秒)时,您会得到与 ZERO 不同的结果。

编辑:注意:从长远来看,microsec_clockWindows 的实现尽可能使用GetSystemTimePreciseAsFileTime 函数(最低要求 Windows 8 桌面、Windows Server 2012 桌面)以实现微秒分辨率。