Linux 下c获取当前时间戳(精确到秒和毫秒或者微秒或者纳秒)
程序员文章站
2024-01-24 08:59:58
...
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:%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<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 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