Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - timespec_get

C Library Function - timespec_get()

C Standard Library - <time.h> C Standard Library -

Description

timespec_get() is a function introduced by the C11 standard, used to obtain the current time and store it in the timespec structure. This function provides a way to obtain precise time and is typically used for high-resolution timing operations.

Declaration

Below is the declaration of the timespec_get() function.



int timespec_get(struct timespec *ts, int base);

Parameters

Return Value

struct timespec structures

struct

timespec

{

    time_t tv_sec

;

 

// Second

   

long

  tv_nsec

;

// nanoseconds

}

;

Example

The following example demonstrates the use of the time() function.

Example

#include

<

stdio.h

#include

<

time.h

int

main

(

)

{

struct

timespec

ts

;

if

(

timespec_get

(

&

ts

,

TIME_UTC

)

==

TIME_UTC

)

{

printf

(

"

Current time: %ld seconds and %ld nanoseconds since the Epoch

\

n

"

,

ts

.

tv_sec

,

ts

.

tv_nsec

)

;

}

else

{

perror

(

"

timespec_get failed

"

)

;

}

return

0

;

}

Let's compile and run the above program, which will produce the following result:



Current time: 1718332786 seconds and 358463000 nanoseconds since the Epoch

Notes

Related functions

By understanding and using timespec_get(), it is convenient to obtain high-precision current time, allowing you to write more efficient and accurate C programs in scenarios that require precise timing.

C Standard Library - <time.h> C Standard Library -