linux时间函数time和gettimeofday

一、time函数   

  1. #include <time.h>
  2. time_t time(time_t *calptr);

返回距计算机元年的秒数
一旦取得这种以秒计的很大的时间值后,通常要调用另一个时间函数将其变换为人们可读的时间和日期

#include <time.h>    
//calendar time into a broken-down time expressed as UTC
struct tm *gmtime(const time_t *calptr);

//converts the calendar time to the local time, taking into account the local time zone and
//daylight saving time flag
struct tm *localtime(const time_t *calptr);

//converts it into a time_t value
time_t mktime(struct tm *tmptr);

  struct tm {        /* a broken-down time */
     int  tm_sec;     /* seconds after the minute: [0 - 60] */
     int  tm_min;     /* minutes after the hour: [0 - 59] */
     int  tm_hour;    /* hours after midnight: [0 - 23] */
     int  tm_mday;    /* day of the month: [1 - 31] */
     int  tm_mon;     /* months since January: [0 - 11] */
     int  tm_year;    /* years since 1900 */
     int  tm_wday;    /* days since Sunday: [0 - 6] */
     int  tm_yday;    /* days since January 1: [0 - 365] */
     int  tm_isdst;   /* daylight saving time flag: <0, 0, >0 */
   };  

  1. char *asctime(const struct tm *tmptr);
  2. char *ctime(const time_t *calptr);
  3.  
  4. asctime()和ctime()函数产生形式的26字节字符串,这与date命令的系统默认输出形式类似:
        Tue Feb 10 18:27:38 2004/n/0
  5. 其实只需要time()和localtime()即可。ctime()和astime()产生的串并不是我们所习惯的,所以可以自己写一个类似ctime()一样的函数,下面是我的代码,大家可以参考,最后输出结果是2012-06-14 17:19这样的字符串,是不是看起来非常顺眼啊。
    复制代码
    #include <stdio.h>
    #include <time.h>
    #include <sys/time.h>
    
    
    int main(int argc,char **argv)
    {
        time_t now;
        struct timeval now_val;
        time(&now);
        struct tm gtime;
        gtime=(*localtime(&now));
        gettimeofday(&now_val,NULL);
        printf("%4d-%02d-%02d %02d:%02d:%02d \n",1900+gtime.tm_year,1+gtime.tm_mon,gtime.tm_mday,gtime.tm_hour,gtime.tm_min,gtime.tm_sec);
    }
    复制代码

     


二、gettimeofday函数得到更精确的时间

  1. #include <sys/time.h>
  2. int gettimeofday(struct timeval *restrict tp, void *restrict tzp);
  3. 第二个形参是基于平台实现的,使用的时候最好用NULL

struct timeval{
    time_t tv_sec;        /*** second ***/
    susecond_t tv_usec;    /*** microsecond 微妙***/
}

1秒=1000毫秒,
1毫秒=1000微秒,
1微妙=1000纳秒,
1纳秒=1000皮秒。
秒用s表现,毫秒用ms,微秒用μs表示,纳秒用ns表示,皮秒用ps表示。

时间比较准

三、总结

   time()和gettimeofday()调用比较占用系统资源,所以不如对时间精度要求不高的情况下,尽量减少调用次数。笔者有次程序出现严重效率问题,最后调试和几天最后定为到了time()这个系统调用上。


转于 :http://www.cnblogs.com/liang-hk/archive/2012/06/14/2549602.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值