头文件:#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; //日光节约时间的状态
    
     };
    
   
    
     
    
   
    
     例子如下
    
   
    
    
   
- 
     
 
 #include<sys/time.h>
 
 
 
 
- 
     
 
 #include<math.h>
 
 
 
 
- 
     
 
 #include<stdio.h>
 
 
 
 
- 
     
 
 int
 
 
 function(
 
 
 void
 
 
 )
 
 
- 
     
 {
 
- 
     
 
 int
 
 
 a=0,b=0,sum=0;
 
 
- 
     
 
 for
 
 
 (;a<300;a++)
 
 
- 
     
 {
 
- 
     
 
 for
 
 
 (;b<=100;b++)
 
 
- 
     
 sum+=b;
 
- 
     
 }
 
- 
     
 
 return
 
 
 sum;
 
 
- 
     
 }
 
- 
     
 
 int
 
 
 main(
 
 
 void
 
 
 )
 
 
- 
     
 {
 
 int
 
 
 sum;
 
 
- 
     
 
 float
 
 
 timeuse;
 
 
- 
     
 
 struct
 
 
 timeval t_start,t_stop;
 
 
- 
     
 gettimeofday(&t_start,NULL);
 
- 
     
 sum=function();
 
- 
     
 gettimeofday(&t_stop,NULL);
 
- 
     
 
 // timeuse=t_stop.tv_sec-t_start.tv_sec+(t_stop.tv_usec-t_start.tv_usec)/1000000;
 
 
 
 
- 
     
 
 // 用这个计算结果是0.000000 精确度不高所至
 
 
 
 
- 
     
 timeuse=(t_stop.tv_sec-t_start.tv_sec)*1000000+t_stop.tv_usec-t_start.tv_usec;
 
- 
     
 timeuse/=1000000 ;
 
- 
     
 printf(
 
 “the programme run %f second/n the result of 1+2+3+….100 is %d/n ”
 
 
 ,timeuse,sum);
 
 
- 
     
 
 return
 
 
 0;
 
 
- 
     
 }
 
 
版权声明:本文为cwzmjy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
