Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1645885
  • 博文数量: 1493
  • 博客积分: 38
  • 博客等级: 民兵
  • 技术积分: 5834
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-19 17:28
文章分类

全部博文(1493)

文章存档

2016年(11)

2015年(38)

2014年(137)

2013年(253)

2012年(1054)

2011年(1)

分类: LINUX

2014-04-19 09:18:13

操作系统:ubuntu10.04

前言:
    在开发中,很多时候需要知道各个函数或者是某些设备对命令的操作用时,因此需要用到 gettimeofday 来获取当前时钟。

一,函数说明

        #include

        int gettimeofday(struct timeval *tv, struct timezone *tz);

        注意:
        1.精确级别,微妙级别
        2.受系统时间修改影响
        3.返回的秒数是从1970年1月1日0时0分0秒开始

        其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:

        结构体timeval的定义为:

点击(此处)折叠或打开

  1. struct timeval
  2. {
  3.     long int tv_sec;     // 秒数
  4.     long int tv_usec;     // 微秒数
  5. }
        它获得的时间精确到微秒(1e-6 s)量级

        结构体timezone的定义为:

点击(此处)折叠或打开

  1. struct timezone
  2. {
  3.     int tz_minuteswest;/*格林威治时间往西方的时差*/
  4.     int tz_dsttime;    /*DST 时间的修正方式*/
  5. }
        timezone 参数若不使用则传入NULL即可。
            其中 tz_dsttime 的值:

点击(此处)折叠或打开

  1. DST_NONE /*不使用*/
  2. DST_USA /*美国*/
  3. DST_AUST /*澳洲*/
  4. DST_WET /*西欧*/
  5. DST_MET /*中欧*/
  6. DST_EET /*东欧*/
  7. DST_CAN /*加拿大*/
  8. DST_GB /*大不列颠*/
  9. DST_RUM /*罗马尼亚*/
  10. DST_TUR /*土耳其*/
  11. DST_AUSTALT /*澳洲(1986年以后)*/

        返回值
            成功则返回0,失败返回-1,错误代码存于errno。

        ERRORS
           EFAULT One of tv or tz pointed outside the accessible address space.
           EINVAL Timezone (or something else) is invalid.



二,实例

点击(此处)折叠或打开

  1. #include <stdio.h>

  2. #include <stdlib.h>

  3. #include <string.h>

  4. #include <sys/time.h>



  5. int    time_substract(struct timeval *result, struct timeval *begin,struct timeval *end)

  6. {

  7.     if(begin->tv_sec > end->tv_sec)    return -1;

  8.     if((begin->tv_sec == end->tv_sec) && (begin->tv_usec > end->tv_usec))    return -2;



  9.     result->tv_sec    = (end->tv_sec - begin->tv_sec);

  10.     result->tv_usec    = (end->tv_usec - begin->tv_usec);

  11.     

  12.     if(result->tv_usec < 0)

  13.     {

  14.         result->tv_sec--;

  15.         result->tv_usec += 1000000;

  16.     }



  17.     return 0;

  18. }





  19. int main(int argc, char **argv)

  20. {

  21.     struct timeval start,stop,diff;



  22.     memset(&start,0,sizeof(struct timeval));

  23.     memset(&stop,0,sizeof(struct timeval));

  24.     memset(&diff,0,sizeof(struct timeval));



  25.     gettimeofday(&start,0);



  26.     //做你要做的事...

  27.     printf("hello world\n");


  28.     gettimeofday(&stop,0);


  29.     time_substract(&diff,&start,&stop);

  30.     printf("Total time : %d s,%d us\n",(int)diff.tv_sec,(int)diff.tv_usec);

  31. }

    操作结果:
        


参考文件:
1,
2,



阅读(809) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~