首頁 >後端開發 >C++ >為什麼`std::chrono::high_resolution_clock`的精確度與測量值不同?

為什麼`std::chrono::high_resolution_clock`的精確度與測量值不同?

Patricia Arquette
Patricia Arquette原創
2024-11-09 06:14:02378瀏覽

Why Does `std::chrono::high_resolution_clock`'s Precision Differ from Measured Values?

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(&amp;frequency);
        return frequency.QuadPart;
    }();
}

HighResClock::time_point HighResClock::now()
{
    LARGE_INTEGER count;
    QueryPerformanceCounter(&amp;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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn