【转】linux下计时器(可以测量程序运行时间)

一般有两个函数的时间分辨率较好:
    1.int gettimeofday(struct timeval *restrict tp, void *restrict tzp);成功返回0,不成功返回-1和错误码errno。
    例:
       

 #include <stdio.h>
        #include <sys/time.h>
        #define MILLION 1000000L
        
        void function_to_time(void);//要测试的函数
        
        int main(void){
            long timedif;
            struct timeval tpend;            //timeval结构体包含两个成员:time_t tv_sec;从Epoch开始的秒数  time_t tv_usec;从Epoch开始的微秒数
            struct timeval tpstart;
            
            if(gettimeofday(&tpstart, NULL)){
                printf(stderr, "Failed to get start time\n");
                return 1;
            }
            
            function_to_time();
            
            if(gettimeofday(&tpend, NULL)){
                printf(stderr, "Failed to get end time\n");
                return 1;
            }
            
            timedif = MILLION*(tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
            printf("The function_to_time took %ld microseconds\n", timedif);
            return 0;
        }

  

posted @ 2014-03-31 14:37  M.Bing  阅读(497)  评论(0编辑  收藏  举报