可参考:https://www.linuxidc.com/Linux/2012-06/61903p2.htm
在计算多线程程序运行时间的时候,用可能会出问题,但是用以下方法会好一些:
#include <iostream>
#include<sys/time.h>
using namespace std;
int delay(int time)
{
int i,j;
for(i =0;i<time;i++)
for(j=0;j<5000;j++)
;
}
int main ()
{
struct timeval start;
struct timeval end;
unsigned long diff;
gettimeofday(&start,NULL);
delay(10);
gettimeofday(&end,NULL);
diff = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec;
printf("thedifference is %ld\n",diff);
return 0;
}