Fork me on GitHub

C++统计程序运行时间代码片段

因为经常需要统计代码的运行时间,所以计时功能就显得很重要,

记录一下现在喜欢用的计时方式,供日后查阅。

1.下面是计时主函数,

bool TimeStaticMine(int id,const char* type)
{ 

    struct TimeInfo
    {
        long long accu_num;
        long long accu_sec;
        long long accu_usec;

        struct timeval st;
        struct timeval ed;
        long long this_time_usec;

        char type[64];
    };
    static TimeInfo info[50];
    
    if(id<0)
    {
        for(int i=0;i<50;i++)memset(info+i,0,sizeof(TimeInfo));
        return true;
    }

    if(type==NULL)
    {
        gettimeofday(&info[id].st,NULL);
        return true;
    }
    gettimeofday(&info[id].ed,NULL);
    info[id].this_time_usec=((info[id].ed.tv_sec)-(info[id].st.tv_sec))*1000000 +
                ((info[id].ed.tv_usec)-(info[id].st.tv_usec));  

    if(info[id].type[0]=='\0') strcpy(info[id].type,type);
    bool needPrint=false;   
    info[id].accu_num++;
    info[id].accu_usec+=info[id].this_time_usec;
 
    char typeData[100];
    sprintf(typeData,"%d-%s",id,info[id].type);

    char tmp[256];
    sprintf(tmp,"=========step: %s, this time: %lld ms=========",typeData,info[id].this_time_usec / 1000);
    printf("%s\n",tmp);
    return true;
}

2.用法如下

 

在每个要计时的函数上定义一个TimeStaticMine,第一个参数为计时id,第二个参数为计时说明。

如下例子分别记录了adjustPic 和probAll两个函数的运行时间。

 

 

posted @ 2019-09-10 10:41  hellowOOOrld  阅读(1827)  评论(0编辑  收藏  举报