Linux下获取时间差(毫秒级)

来源:互联网 发布:阿里云免费证书配置 编辑:程序博客网 时间:2024/06/07 05:24

在基于嵌入式软件系统开发时,针对性能统计,按键响应时间处理等都需要获取时间和时间间隔差等,以下使用Linux的gettimeofday函数即可实现。
其中t1=t_start.tv_sec是公元1970年至今的时间(换算为秒) 
t2=t_start.tv_usec是当前秒数下的微妙数,所以将t1*1000+t2/1000可以得到当前的毫秒数 
判断两次遥控器按键事件或处理事件的时间间隔就容易实现了。

#include <stdio.h> 
#include <sys/time.h> 
#include <time.h>

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

int main(int argc,char * argv[]){ 
     struct timeval t_start,t_end; 
     long cost_time = 0;

     //get start time 
     gettimeofday(&t_start, NULL); 
     long start = ((long)t_start.tv_sec)*1000+(long)t_start.tv_usec/1000; 
     printf("Start time: %ld ms\n", start);

     sleep(2); //秒为单位

     //get end time 
     gettimeofday(&t_end, NULL); 
     long end = ((long)t_end.tv_sec)*1000+(long)t_end.tv_usec/1000; 
     printf("End time: %ld ms\n", end);

     //calculate time slot 
     cost_time = end - start; 
     printf("Cost time: %ld ms\n", cost_time); 
     return 0; 
}

0 0