C++ / Python测量程序执行时间

C++

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

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

#include <iostream>
#include <thread>
#include <chrono>

using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;

void long_operation()
{
    /* 这里模拟一个耗时任务 */
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(150ms);
}

int main()
{
    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;
}

Python

使用time包中的time()方法获取当前时间即可。注意时间差的单位是秒。
具体用法如下面的例子所示:

import time

t1 = time.time()
# do something
t2 = time.time()
print('Time elapsed: ', t2 - t1, 'seconds')
posted @ 2021-07-26 13:44  星夜之夏  阅读(217)  评论(0编辑  收藏  举报