c++ - 使用 boost::posix_time::microsec_clock 的测量误差超过十微秒?

标签 c++ winapi boost time

我有以下代码:

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/

相关文章:

c++ - boost::program_options 可以实现这种可重复的选项吗?

c++ - 试图理解 boost 示例 httpserver3。 shared_ptr 重置方法不清楚

c++ - 我的函数返回一个错误的值 C++

c++ - boost::heap::priority_queue 与 std::priority_queue 的比较器

C++ (de) 序列化项目的 vector 顺序

c - Winapi:获取具有特定文件句柄的进程

c++ - VS 2017 & 2019 找不到 WinRT 头文件,即使是在新的解决方案上

C++在文件中的特定点插入一行

c++ - Windows C++框架推荐

c++ - 为什么 C++11/Boost `unordered_map` 在删除时不重新散列?