C++计算时间差

#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
#include <chrono>
 
volatile int sink;
int main()
{
    std::cout << std::fixed << std::setprecision(9) << std::left;
    for (auto size = 1ull; size < 1000'000'000ull; size *= 100) {
        // record start time
        auto start = std::chrono::system_clock::now();
        // do some work
        std::vector<int> v(size, 42);
        sink = std::accumulate(v.begin(), v.end(), 0u); // make sure it's a side effect
        // record end time
        auto end = std::chrono::system_clock::now();
        std::chrono::duration<double> diff = end-start;
        // 计算毫秒时间差并输出
        // 如果要求其他时间单位可以修改 std::chrono::milliseconds 为其他类型
        // 比如std::chrono::seconds
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
        std::cout << "Time to fill and iterate a vector of " << std::setw(9)
                  << size << " ints : " << duration.count()  << " ms\n";
    }
}
posted @ 2022-08-14 00:28  hiccup_lh  阅读(425)  评论(0编辑  收藏  举报