Linux下获取毫秒级时间差

使用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); 
usleep(5000);//5毫秒
//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; 




提供一些相关的资料: 
http://book.chinaunix.net/special/ebook/addisonWesley/APUE2/0201433079/ch06lev1sec10.html 
http://www.linuxidc.com/Linux/2010-09/28318.htm 
http://blog.sina.com.cn/s/blog_62a9b1bb0100seyz.html 
http://lizzy115.blog.163.com/blog/static/36491958201102505054953/
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值