Linux下可以使用gettimeofday()来查看当前时间,这个函数会计算从1970年1月1号00:00(格林威治时间)到当前的时间跨度。其函数原型如下
函数原型:
#include<sys/time.h>
int gettimeofday(struct timeval *tv,struct timezone *tz)
该函数所算出的时间跨度会存放在第一个参数结构体变量tv里,这个参数的类型定义如下,
struct timeval
{
long tv_sec; //秒
long tv_usec; //微秒
}
代码:
如下是该函数一个简单应用,计算一个函数运算时间
#include<stdio.h>
#include<sys/time.h>
void cntTest() //定义一个需要计算运行时间的函数
{
int i,j;
for(i=0;i<100;i++){
for(j=0;j<1000;j++){
}
}
}
int main()
{
long difference;
struct timeval timestart; //函数调用之前时间
struct timeval timestop; //函数调用之后时间
gettimeofday(×tart,NULL);
cntTest();
gettimeofday(×top,NULL);
difference=1000000*(timestop.tv_sec-timestart.tv_sec)+(timestop.tv_usec-timestart.tv_usec); //计算出的结果,以us为单位
printf("time start: sec = %ld,usec = %ld\n",timestart.tv_sec,timestart.tv_usec);
printf("time stop: sec = %ld,usec = %ld\n",timestop.tv_sec,timestop.tv_usec);
printf("diffefence: %ld us\n",difference);
return 0;
}