gettimeofday 函数

使用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

【参考】百度百科

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值