Linux系统获取用户空间ns级时间精度——clock_gettime
程序员文章站
2024-01-21 22:33:04
...
clock_gettime函数原型如下:
long sys_clock_gettime (clockid_t which_clock, struct timespec *tp);
1.which_clock CLOCK_REALTIME: 系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时
CLOCK_MONOTONIC: 从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
CLOCK_PROCESS_CPUTIME_ID: 本进程到当前代码系统CPU花费的时间
CLOCK_THREAD_CPUTIME_ID: 本线程到当前代码系统CPU花费的时间
2.struct timespec
struct timespec
{
time_t tv_sec;
long int tv_nsec;
};
3.示例
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
struct timespec time_start = {0, 0}, time_end = {0, 0};
clock_gettime(CLOCK_REALTIME, &time_start); // 获取当前时间
printf("start time %llus, %lluns\n", time_start.tv_sec, time_start.tv_nsec);
clock_gettime(CLOCK_REALTIME, &time_end); // 上一条打印语句执行之后,获取当前时间
printf("end time %llus, %lluns\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 -g test.c -o test
运行:
./test
结果:
start time 1528767558s, 733149781ns
end time 1528767558s, 733188709ns
duration: 0s 38928ns