gettimeofday()用法

头文件:#include <sys/time.h>    #include <unistd.h>

定义函数:int gettimeofday (struct timeval * tv, struct timezone * tz);

函数说明:gettimeofday()会把目前的时间有tv 所指的结构返回,当地时区的信息则放到tz 所指的结构中。

timeval 结构定义为:
struct timeval{
    long tv_sec;  //秒
    long tv_usec;  //微秒
};

timezone 结构定义为:
struct timezone
{
    int tz_minuteswest;  //和Greenwich 时间差了多少分钟
    int tz_dsttime;  //日光节约时间的状态

};


例子如下

  1. #include<sys/time.h>  
  2. #include<math.h>  
  3. #include<stdio.h>  
  4. int function(void)  
  5. {  
  6.     int a=0,b=0,sum=0;  
  7.     for(;a<300;a++)  
  8.     {  
  9.     for(;b<=100;b++)  
  10.     sum+=b;  
  11.     }  
  12.     return sum;  
  13. }  
  14. int main(void)  
  15. {   int sum;  
  16.     float timeuse;  
  17.     struct timeval t_start,t_stop;  
  18.     gettimeofday(&t_start,NULL);  
  19.     sum=function();  
  20.     gettimeofday(&t_stop,NULL);  
  21. //  timeuse=t_stop.tv_sec-t_start.tv_sec+(t_stop.tv_usec-t_start.tv_usec)/1000000;  
  22. //  用这个计算结果是0.000000 精确度不高所至  
  23.     timeuse=(t_stop.tv_sec-t_start.tv_sec)*1000000+t_stop.tv_usec-t_start.tv_usec;  
  24.     timeuse/=1000000 ;  
  25.     printf("the programme run %f second/n the result of 1+2+3+....100 is %d/n ",timeuse,sum);  
  26.     return 0;  
  27. }  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值