使用C语言编写程序需要获得当前精确时间(1970年1月1日到现在的时间),或者为执行计时,可以使用gettimeofday()函数。
库为 #include <sys/time.h>
函数原型
int gettimeofday(struct timeval*tv, struct timezone *tz);
说明
gettimeofday()会把目前的时间用tv结构体返回,当地时区的信息则放到tz所指的结构中
结构体
struct timeval{
long tv_sec; //秒
long tv_usec;//微秒
};
struct timezone{
int tz_minuteswest;//和greenwich时间查了多少分钟
int tz_dsttime; //DST 时间的修正方式
}
在gettimeofday()函数中的俩个参数都可以为NULL,为NULL时对应的结构体将不返回值。
返回值 0 成功;-1失败,原因存于errno;
举例代码
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main()
{
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
printf("tv_sec:%d\n",tv.tv_sec);
printf("tv_usec:%d\n",tv.tv_usec);
printf("tz_minuteswest:%d\n",tz.tz_minuteswest);
printf("tz_dsttime:%d\n",tz.tz_dsttime);
}
运行结果
举例2
计算某个函数执行时间(单位为微妙)
代码
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int delay(int time)
{
int i, j;
for(i = 0; i < time; i++)
for(j = 0; j < 5000; j++);
}
/**********************************************
*
* 查看delay()函数的执行时间
*
* ********************************************/
int main()
{
struct timeval start;
struct timeval end;
unsigned long diff;
gettimeofday(&start, NULL);
delay(10);
gettimeofday(&end, NULL);
diff = 1000*(end.tv_sec - start.tv_sec) + end.tv_usec - start.tv_usec;
printf("thw difference is %ld \n",diff);
return 0;
}
运行结果
【参考】http://www.linuxidc.com/Linux/2012-06/61903p2.htm
【参考】百度百科