c++11:计算时间差(毫秒)

2021-03-22 10:14:59 浏览数 (1)

C 11下计算时间差(毫秒)要用到chrono时间库,以下是示例代码,我从en.cppreference.com上抄来改的.

代码语言:javascript复制
#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()  << " msn";
    }
}

0 人点赞