Skip to main content
 首页 » 操作系统

Linux 获取程序段执行时间

2022年07月19日23JustinYoung

struct timeval pre_time, now_time;
unsigned int time;

gettimeofday(&pre_time, NULL);
要测试的程序段
gettimeofday(&now_time, NULL);


time = (now_time.tv_sec - pre_time.tv_sec) * 1000000;
time += now_time.tv_usec;
time -= pre_time.tv_usec;

printf("pass time = %d [us]\n", time);

这是错误的
/*
* start_stop : 0 start,1 stop * distinguish: used to distinguish each other */ void print_time(int start_stop, int distinguish) { uint64_t diff_time, diff_sec, diff_usec; static struct timeval pre_time, now_time; if(!start_stop) { pre_time.tv_sec = 0; pre_time.tv_usec = 0; now_time.tv_sec = 0; now_time.tv_usec = 0; gettimeofday(&pre_time, NULL); } else { gettimeofday(&now_time, NULL); diff_sec = now_time.tv_sec - pre_time.tv_sec; diff_usec = now_time.tv_usec - pre_time.tv_usec; diff_time = (diff_sec * 1000000 + diff_usec) / 1000; dbg_printf("[%d]: diff_time=%lu ms\n", distinguish, diff_time); } }
这是错误的!
/*
* start_stop : 0 start,1 stop * distinguish: used to distinguish each other */ void print_time(int start_stop, int distinguish) { uint32_t diff_time, diff_sec, diff_usec; static struct timeval pre_time, now_time; if(!start_stop) { pre_time.tv_sec = 0; pre_time.tv_usec = 0; now_time.tv_sec = 0; now_time.tv_usec = 0; gettimeofday(&pre_time, NULL); } else { gettimeofday(&now_time, NULL); diff_sec = now_time.tv_sec - pre_time.tv_sec; diff_usec = now_time.tv_usec - pre_time.tv_usec; diff_time = diff_sec * 1000 + diff_usec / 1000; dbg_printf("[%d]: diff_time=%d ms\n", distinguish, diff_time); } }
/* 
 * start_stop : 0 start,1 stop 
 * distinguish: used to distinguish each other 
 */ 
void print_time(int start_stop, int distinguish) 
{ 
    uint64_t diff_time, diff_sec, diff_usec; 
    static struct timeval pre_time, now_time; 
 
    if(!start_stop) { 
        pre_time.tv_sec  = 0; 
        pre_time.tv_usec = 0; 
        now_time.tv_sec  = 0; 
        now_time.tv_usec = 0; 
        gettimeofday(&pre_time, NULL); 
    } else { 
        gettimeofday(&now_time, NULL); 
     
        diff_sec  = now_time.tv_sec  - pre_time.tv_sec; 
        diff_usec = now_time.tv_usec > pre_time.tv_usec ? 
            now_time.tv_usec - pre_time.tv_usec : 
            pre_time.tv_usec - now_time.tv_usec ; 
        diff_time = (diff_sec * 1000000 + diff_usec) / 1000; 
        dbg_printf("[%d]: diff_time=%lu ms\n", distinguish, diff_time); 
    } 
}

这个比较好用:

#define print_log_with_time(fmt, args...)                                          \ 
do {                                                                          \ 
        struct timespec ts;                                               \ 
        clock_gettime(CLOCK_MONOTONIC,&ts);                               \ 
        fprintf(stderr,"[%5lu.%06lu] initsvscripts %s:%d: " fmt "\n",    \ 
                    ts.tv_sec, ts.tv_nsec / 1000, __func__, __LINE__, ##args);    \ 
    } while (0)

本文参考链接:https://www.cnblogs.com/hellokitty2/p/8053839.html