Linux 下c获取当前时间戳(精确到秒和毫秒或者微秒或者纳秒) - Go语言中文社区

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


t.c源码:

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

int main(){
    struct timeval tv;
    gettimeofday(&tv,NULL);
    printf("second:%ldn",tv.tv_sec);  //秒
    printf("millisecond:%ldn",tv.tv_sec*1000 + tv.tv_usec/1000);  //毫秒
    printf("microsecond:%ldn",tv.tv_sec*1000000 + tv.tv_usec);  //微秒

    sleep(3); // 为方便观看,让程序睡三秒后对比
    printf("------------------------------n");
    gettimeofday(&tv,NULL);
    printf("second:%ldn",tv.tv_sec);  //秒
    printf("millisecond:%ldn",tv.tv_sec*1000 + tv.tv_usec/1000);  //毫秒
    printf("microsecond:%ldn",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<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
    struct timespec time_start={0, 0},time_end={0, 0};
    clock_gettime(CLOCK_REALTIME, &time_start);
    printf("start time %llus,%llu nsn", time_start.tv_sec, time_start.tv_nsec);
    clock_gettime(CLOCK_REALTIME, &time_end);
    printf("endtime %llus,%llu nsn", time_end.tv_sec, time_end.tv_nsec);
    printf("duration:%llus %llunsn", 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

 

转载于:https://my.oschina.net/lenglingx/blog/1488566

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34102807/article/details/92059610
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-27 20:44:37
  • 阅读 ( 1494 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢