C/C++ 计时

写代码,测试代码性能的时候往往需要测量代码执行时间,这时候就需要计时。现总结自己常用的计时方式如下:

c方式的计时

#include 

    double dur;
    clock_t start, end;
    start = clock();

    // operations 

    end = clock();
    dur = (double)(end - start);
    printf("Use Time:%f\n", (dur*1000 / CLOCKS_PER_SEC)); // ms

c++ 11 chrono方式的计时

#include 

    auto start = std::chrono::steady_clock::now();

    // operations

    auto end = std::chrono::steady_clock::now();
    std::chrono::duration elapsed_seconds = end-start;
    std::cout << "It took " << elapsed_seconds.count() << " seconds.";

你可能感兴趣的:(C/C++ 计时)