zoukankan      html  css  js  c++  java
  • 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 <chrono>
    
    #include <iostream>
    #include <thread>
    
    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()
    {
        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
    ";
        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')
    
  • 相关阅读:
    Mysql配置文件解析
    Mysql的视图
    Setup和 Hold
    洛谷 P2257
    洛谷 P3455
    洛谷 P1447
    洛谷 P1155
    洛谷 P1262
    洛谷 P4180
    洛谷 P5540
  • 原文地址:https://www.cnblogs.com/xia-weiwen/p/15061036.html
Copyright © 2011-2022 走看看