Rate This Document
Findability
Accuracy
Completeness
Readability

clock_gettime

Function Usage

Obtains the number of seconds and nanoseconds returned by CLOCK_REALTIME since January 1, 1970. This function is used to obtain high-precision timestamps.

Function Syntax

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

Parameters

Parameter

Description

Value Range

Input/Output

clk_id

Clock source

CLOCK_REALTIME only

Input

tp

Pointer to timespec, which stores the obtained time

Non-null timespec structure

Input/Output

Return Value

  • Success: 0 is returned.
  • Failure: If tp is null, the KPGLIBC_STS_PARAMETER_ERR error code is returned.

The precision of the time obtained using clock_gettime is nanoseconds.

Example

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

int main() 
{
    struct timespec ts;
    if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
        perror("clock_gettime error");
        return 1;
    }
    printf("Current time: %ld seconds %ld nanoseconds\n", ts.tv_sec, ts.tv_nsec);
    return 0;
}

Output:

Current time: *** seconds *** nanoseconds