zoukankan      html  css  js  c++  java
  • 精确记算程序的运行时间或者某段代码的运行时间

         程序的运行效率很重要,为了明确到底是那一块代码浪费时间,浪费多少时间,检测一下是很有必要的,用下面的方法可以精确地统计时间。第一种精确到,第二种精确到毫秒,第三种精确到0.000001秒,大家可以根据自己的需求选用。

    #include<time.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<windows.h>
    int main()
    {
        //精确到秒 ==========================================
        time_t t1,t2;
        time(&t1);
        //此处放置要测试的代码
        Sleep(1000);//延时 
        time(&t2);
        printf("%d %d %d秒\n",t1,t2,t2-t1);
        //精确到毫秒 ========================================
        clock_t c1,c2;
        c1=clock();
        //此处放置要测试的代码
        Sleep(100);//延时 
        c2=clock();
        printf("%d %d %d毫秒\n",c1,c2,c2-c1);
        //精确到 0.000001毫秒 ===============================
        LARGE_INTEGER litmp;
        LONGLONG start, end;
        double dft, dff, dfm;
        QueryPerformanceFrequency(&litmp);//获得时钟频率
        dff = (double) litmp.QuadPart;
        QueryPerformanceCounter(&litmp);//获得初始值
        start = litmp.QuadPart; 
        //此处放置要测试的代码
        Sleep(1000);//延时
        QueryPerformanceCounter(&litmp);//获得终止值
        end = litmp.QuadPart;
        dfm = (double) (end - start);
        dft = dfm / dff;//获得对应的时间值,单位秒
        printf("%lf毫秒\n",dfm/dff*1000);
    }
    运行截图

     那是在windows下的,如果在linux环境下,要这样计算时间:

    struct timeval tv_start,tv_end;

    gettimeofday(&tv_start,NULL);
    //此处放要测试的代码或程序
    gettimeofday(&tv_end,NULL);
    printf("程序运行时间为:%lf秒\n",tv_end.tv_sec-tv_start.tv_sec+(tv_end.tv_usec-tv_start.tv_usec)/1000000.0); 

    其中timeval的结构题定义是这样的:

    struct timeval {
        time_t      tv_sec;     /* seconds */
        suseconds_t tv_usec;    /* microseconds 微秒=1/10^6秒 */
    }; 

    tv_sec和tv_usec可以单独输出,根据自己的需求选择精度就可以了

  • 相关阅读:
    CPU问题导致的大量进程崩溃问题
    coredump的裁剪方法
    GDB中遍历art::Thread打印local reference的脚本
    jemalloc管理块(arena、bin)
    jemalloc存储块(region、run、chunk)
    GDB中打印pthread_internal_t的方法
    FUSE引起的SIGBUS问题分析报告
    GDB中打印ART基础类
    UC浏览器闪退问题分析报告
    『深度实战』天池小目标检测大赛·宫颈癌风险智能诊断推荐
  • 原文地址:https://www.cnblogs.com/ma6174/p/2310996.html
Copyright © 2011-2022 走看看