计算代码段的执行时间,这段代码用得太多了。决定将其封装成两个宏,方便以后使用。
代码非常easy,就不解释了。
#include <stdio.h> #include <sys/time.h> //计时器開始, //使用时,要将要计时的代码段放入TIMER_START和TIMER_STOP之间。详情请看測试样例 //增加do{ }while(0)是为了尽量降低命令冲突 #define TIMER_START() \ do \ { \ struct timeval timerout_start, timerout_end, timerout_spend; \ gettimeofday(&timerout_start, NULL); //计时器结束。将參数res设为代码段的耗时,单位是秒 #define TIMER_STOP(res) \ gettimeofday(&timerout_end, NULL); \ timersub(&timerout_end, &timerout_start, &timerout_spend); \ res = timerout_spend.tv_sec + (timerout_spend.tv_usec / 1.0e6); \ } while (0); //測试样例 int main() { double ddd; TIMER_START(); sleep(1); TIMER_STOP(ddd); printf("speed time: %lfs\n", ddd); TIMER_START(); sleep(3); TIMER_STOP(ddd); printf("speed time: %lfs\n", ddd); return 0; }