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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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

 

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

你可能感兴趣的:(Linux 下c获取当前时间戳(精确到秒和毫秒或者微秒或者纳秒))