std::chrono::high_resolution_clock精確度為何與測量值不符?
問題:
在以下測試程序中,程式試圖測量std::cout的執行時間,但得到的測量結果並不一致,總是1 或2 微秒。這是因為std::chrono::high_resolution_clock的精確度似乎不是 100 奈秒,或是測量std::cout執行時間的程式碼有問題。
#include <iostream> #include <chrono> using std::chrono::nanoseconds; using std::chrono::duration_cast; int main() { std::cout << "Resolution (nano) = " << (double) std::chrono::high_resolution_clock::period::num / std::chrono::high_resolution_clock::period::den * 1000 * 1000 * 1000 << std::endl; auto t1 = std::chrono::high_resolution_clock::now(); std::cout << "How many nanoseconds does std::cout take?" << std::endl; auto t2 = std::chrono::high_resolution_clock::now(); auto diff = t2 - t1; nanoseconds ns = duration_cast<nanoseconds>(diff); std::cout << "std::cout takes " << ns.count() << " nanoseconds" << std::endl; }
回答:
在Visual Studio 2012 中,std::chrono::high_resolution_clock 被定義為system_clock,這導致了較差的精度(大約1 毫秒)。為了獲得更高的精度,可以使用以下自定義的高分辨率時鐘:
HighResClock.h
struct HighResClock { typedef long long rep; typedef std::nano period; typedef std::chrono::duration<rep, period> duration; typedef std::chrono::time_point<HighResClock> time_point; static const bool is_steady = true; static time_point now(); };
HighResClock.cpp
namespace { const long long g_Frequency = []() -> long long { LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); return frequency.QuadPart; }(); } HighResClock::time_point HighResClock::now() { LARGE_INTEGER count; QueryPerformanceCounter(&count); return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency)); }
可以使用這個時鐘來取代std::chrono::high_resolution_clock進行高精度時間測量。
以上是為什麼`std::chrono::high_resolution_clock`的精確度與測量值不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!