本文将介绍两种程序运行时间测量方法。
方法一
int main(void)
{
struct timeval start, end;
long secs_used, micros_used;
gettimeofday(&start, NULL); /* Time on */
for(int i = 0; i < 1000; i++)
{
/* Do something */
}
gettimeofday(&end, NULL); /* Time out */
secs_used=(end.tv_sec - start.tv_sec); //avoid overflow by subtracting first
micros_used= (secs_used * 1000000) + (end.tv_usec - start.tv_usec);
printf("time used: %ld us\n",micros_used);
}
方法二
int main(void)
{
double time = 0;
clock_t clock_timer;
clock_timer = clock(); /* Time on */
for(int i = 0; i < 1000; i++)
{
/* Do something */
}
time = (double) (clock() - clock_timer) / CLOCKS_PER_SEC; /* Time out */
printf("time used: %d s\n",time);
}
注:方法一要精确一些。