码迷,mamicode.com
首页 > 其他好文 > 详细

时间处理

时间:2016-07-01 11:36:47      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

ref: http://www.cnblogs.com/xmphoenix/archive/2011/05/09/2041546.html

 

#include <unistd.h> //sleep() 秒 usleep()微妙

#include <time.h> 

/*

int nanosleep(const struct timespec *req, struct timespec *rem);

 struct timespec
              {
                      time_t  tv_sec;         /* seconds */
                      long    tv_nsec;        /* nanoseconds */
              };

这个函数功能是暂停某个进程直到你规定的时间后恢复,参数req就是你要暂停的时间,其中req->tv_sec是以秒为单位,而tv_nsec以毫微秒为单位(10的-9次方秒)。

由于调用nanosleep是是进程进入TASK_INTERRUPTIBLE,这种状态是会相应信号而进入TASK_RUNNING状态的,

这就意味着有可能会没有等到你规定的时间就因为其它信号而唤醒,此时函数返回-1,切还剩余的时间会被记录在rem中。

*/

 

#include <sys/time.h> 

/*

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

其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:
struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}
timezone 参数若不使用则传入NULL即可。
而结构体timeval的定义为:
struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}

*/

 

计算时间差值

int timeval_subtract(struct timeval* result, struct timeval* x, struct timeval* y)
{   
    int nsec;
    
    if ( x->tv_sec>y->tv_sec )
        return -1;
    
    if ( (x->tv_sec==y->tv_sec) && (x->tv_usec>y->tv_usec) )
        return -1;
    
    result->tv_sec = ( y->tv_sec-x->tv_sec ); 
    result->tv_usec = ( y->tv_usec-x->tv_usec );
    
    if (result->tv_usec<0)
    {   
        result->tv_sec--;
        result->tv_usec+=1000000;
    }
    
    return 0;
}


struct timeval start,stop,diff;
gettimeofday(&start,0);
printf( "CAPABILITY_1_SECS_%010u_USEC_%010u\n", start.tv_sec, start.tv_usec );

gettimeofday(&stop,0);
printf( "CAPABILITY_2_SECS_%010u_USEC_%010u\n", stop.tv_sec, stop.tv_usec );

timeval_subtract(&diff,&start,&stop);
printf( "CAPABILITY_3_SECS_%010u_USEC_%010u\n", diff.tv_sec, diff.tv_usec );

 

时间处理

标签:

原文地址:http://www.cnblogs.com/kaishan1990/p/5632382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!