clock_gettime( ) 提供了纳秒级的精确度
1、头文件 <time.h>
2、编译&链接。在编译链接时需加上 -lrt ;因为在librt中实现了clock_gettime函数
3、函数原型
int clock_gettime(clockid_t clk_id, struct timespect *tp);
参数说明:
clockid_t clk_id 用于指定计时时钟的类型,有以下4种:
CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户该成其他,则对应的时间相应改变
CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间
CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
struct timespect *tp用来存储当前的时间,其结构如下:
struct timespec
{
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
返回值。0成功,-1失败
#include<stdio.h>
#include<time.h>
int main()
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
printf("CLOCK_REALTIME: %d, %d", ts.tv_sec, ts.tv_nsec);
clock_gettime(CLOCK_MONOTONIC, &ts);//打印出来的时间跟 cat /proc/uptime 第一个参数一样
printf("CLOCK_MONOTONIC: %d, %d", ts.tv_sec, ts.tv_nsec);
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
printf("CLOCK_PROCESS_CPUTIME_ID: %d, %d", ts.tv_sec, ts.tv_nsec);
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts);
printf("CLOCK_THREAD_CPUTIME_ID: %d, %d", ts.tv_sec, ts.tv_nsec);
printf("/n%d/n", time(NULL));
return 0;
}
/proc/uptime里面的两个数字分别表示:
the uptime of the system (seconds), and the amount of time spent in idle process (seconds).
把第一个数读出来,那就是从系统启动至今的时间,单位是秒