c linux time微秒_Linux 下c获取当前时间戳(精确到秒和毫秒或者微秒或者纳秒)...

t.c源码:

#include

#include

#include

#include

int main(){

struct timeval tv;

gettimeofday(&tv,NULL);

printf("second:%ld\n",tv.tv_sec); //秒

printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒

printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒

sleep(3); // 为方便观看,让程序睡三秒后对比

printf("------------------------------\n");

gettimeofday(&tv,NULL);

printf("second:%ld\n",tv.tv_sec); //秒

printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒

printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒

return 0;

}

运行:

$ ./t

second:1501000012

millisecond:1501000012738

microsecond:1501000012738594

------------------------------

second:1501000015

millisecond:1501000015738

microsecond:1501000015738717

--- 获取纳秒级别的 ---

t1.c源码:

#include

#include

#include

int main(void)

{

struct timespec time_start={0, 0},time_end={0, 0};

clock_gettime(CLOCK_REALTIME, &time_start);

printf("start time %llus,%llu ns\n", time_start.tv_sec, time_start.tv_nsec);

clock_gettime(CLOCK_REALTIME, &time_end);

printf("endtime %llus,%llu ns\n", time_end.tv_sec, time_end.tv_nsec);

printf("duration:%llus %lluns\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec);

return 0;

}

编译:

gcc -o t1 t1.c -lrt

运行:

$ ./t1

start time 1501001451s,320841750 ns

endtime 1501001451s,320881827 ns

duration:0s 40077ns

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值