Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1213603
  • 博文数量: 261
  • 博客积分: 4196
  • 博客等级: 上校
  • 技术积分: 3410
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-17 17:05
文章分类

全部博文(261)

文章存档

2018年(1)

2017年(22)

2016年(2)

2015年(8)

2014年(27)

2013年(40)

2012年(161)

分类: LINUX

2012-04-17 10:12:43

form:luozhiyong131.blog.chinaunix.net


gettimeofday 例子程序 计算时间差

void function() 
{ 
 unsigned int i,j; 
 double y; 
 for(i=0;i<1000;i++) 
 for(j=0;j<1000;j++) 
 y=sin((double)i); //耗时操作
} 

main() 
{ 
 struct timeval tpstart,tpend; 
 float timeuse; 

 gettimeofday(&tpstart,NULL); //记录开始时间戳
 function(); 
 gettimeofday(&tpend,NULL); //记录结束时间戳
 timeuse = 1000000*(tpend.tv_sec-tpstart.tv_sec)+ 
tpend.tv_usec-tpstart.tv_usec; //计算差值
 timeuse /= 1000000; 
 printf("Used Time:%f\n",timeuse); 
 exit(0); 
} 

GNU/Linux提供了各种各样的处理时间的函数(日期和时间),时间通常用tm结构体表示:

struct   tm

{

      int   tm_sec;            /*0-59的秒数*/

      int   tm_min;            /* 0-59的分数 */

      int   tm_hour;         /* 0-23的小时数 */

      int   tm_mday;       /*1-31的日期数*/

      int   tm_mon;         /*0-11的月数*/

      int   tm_year;         /* 1900 年算起至今的年数 */

      int   tm_wday;       /*0-6的星期数 0=Sunday */

      int   tm_yday;       /*0-365的天数*/

      int   tm_isdst;       /*日光节约时间的旗标(0,1-1*/

};

 

#include

time_t time(time_t *t); //取得目前的时间,返回从公元197011UTC时间从000秒算起到现在所经过的秒数

struct tm *localtime(const time_t *timep); //取得当地目前时间和日期,时间日期已经转换成当地时区

struct tm *gmtime(const time_t *timep); //取得目前时间和日期,UTC时间

char *asctime(const struct tm *tm);//将时间和日期以字符串格式表示

char *ctime(const time_t *timepDay); //将时间和日期以字符串格式表示

time_t mktime(struct tm *tm); //将时间结构数据转换成从公元197011000 秒算起至今的UTC时间所经过的秒数

 

注:UTC世界协调时间

 

 

  1. /*
  2.  *    时间API    
  3.  *    Lzy        2011-6-12
  4.  */

  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <time.h>

  8. int main(void)
  9. {
  10.     time_t tt;        //定义变量
  11.     struct tm *t;
  12.     
  13.     tt = time(NULL);    //取得目前的时间,从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数
  14.     t = localtime(&tt);    //取得当地目前时间和日期,时间日期已经转换成当地时区
  15.     printf("%s",asctime(t));    //将时间和日期以字符串格式表示
  16.     
  17.     return 0;
  18. }
  1. /*
  2.  * 时间函数
  3.  */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <time.h>

  7. int main(void)
  8. {
  9.     time_t tt;
  10.     struct tm * ttm;
  11.     
  12.     tt = time(NULL);    //获取系统时间
  13.     
  14.     ttm = localtime(&tt);
  15.     printf("local time is: %s\n",
  16.             asctime(ttm));
  17.             
  18.     ttm = gmtime(&tt);
  19.     printf("gm time is: %s\n",
  20.             asctime(ttm));
  21.             
  22.     return 0;
  23. }
阅读(1139) | 评论(0) | 转发(2) |
给主人留下些什么吧!~~