linux clock_gettime函数详解

long sys_clock_gettime (clockid_t which_clock, struct timespec *tp);

which_clock参数解释

CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户该成其他,则对应的时间相应改变

CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响

CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间

CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间


//test9.c

#include
#include

int main()
{
struct timespec time1 = {0, 0};
clock_gettime(CLOCK_REALTIME, &time1);
printf("CLOCK_REALTIME: %d, %d", time1.tv_sec, time1.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &time1);
printf("CLOCK_MONOTONIC: %d, %d", time1.tv_sec, time1.tv_nsec);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
printf("CLOCK_PROCESS_CPUTIME_ID: %d, %d", time1.tv_sec, time1.tv_nsec);
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &time1);
printf("CLOCK_THREAD_CPUTIME_ID: %d, %d", time1.tv_sec, time1.tv_nsec);

printf("/n%d/n", time(NULL));
sleep(1);
}

如果无法编译,默认没有加入该库,请用gcc test9.c -lrt运行

测试 #time ./a.out

你可能感兴趣的:(编程语言)