1. 程式人生 > 其它 >C++ 測量程式執行時間

C++ 測量程式執行時間

參考:https://stackoverflow.com/questions/22387586/measuring-execution-time-of-a-function-in-c

C++11中提供了非常好用的工具,也就是使用<chrono>中定義的std::chrono::high_resolution_clock
用法直接看例子:

#include <chrono>

#include <iostream>
#include <thread>
    
void long_operation()
{
    /* 這裡模擬一個耗時任務 */
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(150ms);
}

int main()
{
    using std::chrono::high_resolution_clock;
    using std::chrono::duration_cast;
    using std::chrono::duration;
    using std::chrono::milliseconds;

    auto t1 = high_resolution_clock::now(); // 獲得當前時間
    long_operation(); // 執行任務
    auto t2 = high_resolution_clock::now(); // 獲得當前時間

    /* 獲得時間差(整數,毫秒) */
    auto ms_int = duration_cast<milliseconds>(t2 - t1);

    /* 獲得時間差(浮點數,毫秒) */
    duration<double, std::milli> ms_double = t2 - t1;

    /* 列印時間差 */
    std::cout << ms_int.count() << " ms\n";
    std::cout << ms_double.count() << " ms";
    return 0;
}