欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言时间函数(5)之clock_gettime()

程序员文章站 2024-01-21 21:22:46
...

1、clock_gettime(获取指定时钟的时间值)

#include <time.h>

int clock_gettime( clockid_t clock_id,struct timespec * tp );

说明:clock_id指定要获取时间的时钟,根据Posix的指定可以是以下值:

CLOCK_REALTIME       0

Systemwide realtime clock.

 

CLOCK_MONOTONIC     1

Represents monotonic time. Cannot be set.

 

CLOCK_PROCESS_CPUTIME_ID    2

High resolution per-process timer.

 

CLOCK_THREAD_CPUTIME_ID      3

Thread-specific timer.

 

CLOCK_REALTIME_HR                4

High resolution version of CLOCK_REALTIME.

 

CLOCK_MONOTONIC_HR            5

High resolution version of CLOCK_MONOTONIC.

 

获取数据的结构体定义如下:

struct timespec {

time_t tv_sec;        /* seconds */

long  tv_nsec;       /* nanoseconds 纳秒*/

};

例子:

#include<stdio.h>
#include<time.h>

int main()
{
    time_t timeval =0;
    struct timespec st;

    clock_gettime(CLOCK_REALTIME,&st);
    time(&timeval);

    printf("timeval = %ld\nclock_gettime val = %ld\n",timeval,st.tv_sec);

    return 0;
}

结果:

C语言时间函数(5)之clock_gettime()


当然还有其他很多函数,比如adjxtime(),比如

C语言时间函数(5)之clock_gettime()

其他的实际用到的时候再学习。