距离上次更新本文已经过去了 512 天,文章部分内容可能已经过时,请注意甄别
函数的基本信息如下
- 其中第一个参数是配置你想获取什么类型的时间
- 第二个参数是一个输出型参数,会将当前时间存放到一个结构体里面给你返回。
- 返回值标识是否获取成功
1 2 3 4 5 6 7 8 9 10 11
| #include <time.h>
int clock_gettime( clockid_t clock_id,struct timespec * tp );
struct timespec { __time_t tv_sec; __syscall_s long_t tv_nsec; };
|
第一个参数有下面几种选项
1 2 3 4
| CLOCK_REALTIME: 是指系统时间,随着系统时间的改变而改变。系统时钟会被用户而改变。并非不变的时间戳。 CLOCK_MONOTONIC: 指从系统启动时开始计时。不受系统设置影响,也不会被用户改变。 CLOCK_PROCESS_CPUTIME_ID: 指这个进程运行到当前代码时,CPU花费的时间。 CLOCK_THREAD_CPUTIME_ID: 指这个线程运行到当前代码时,CPU花费的时间。
|
使用例子
1 2 3 4 5 6 7 8 9 10 11 12
| #include<stdio.h> #include<time.h>
int main(){ struct timespec now;
clock_gettime(CLOCK_MONOTONIC,&now);
printf("Seconds = %ld \t Nanoseconds = %ld\n",, now.tv_sec, now.tv_nsec);
return 0; }
|
输出结果
1
| Seconds = 29642 Nanoseconds = 751516090
|