首页 > 编程语言 > 详细

C++ 测量程序执行时间

时间:2021-07-26 14:47:15      阅读:17      评论:0      收藏:0      [点我收藏+]

参考: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;
}

C++ 测量程序执行时间

原文:https://www.cnblogs.com/xia-weiwen/p/15061036.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!