What is timespec in C?

The structure timespec is defined in the time.h library of C and is used to store data such as time-elapsed. It allows the user to store time in seconds and nanoseconds.

The time.h library must be included in the program to use the timespec structure as we see here:

#include <time.h>

Declaration

struct timespec {
    time_t tv_sec;
    long tv_nsec;
};

The timespec struct contains two member variables:

  • tv_sec – The variable of the time_t type made to store time in seconds.
  • tv_nsec – The variable of the long type used to store time in nanoseconds.

Both variables are public by default as timespec is a struct.

Example

The code snippet below demonstrates how we may use member variables of the timespec structure to store time-elapsed in seconds and nanoseconds.

We declare a struct of type timespecand set the values of tv_sec and tv_sec to 56 and 100, respectively. Each member variable is accessed using the dot notation, and we may reset its value at any point in time in the code. The printf function is used to print the values set by the programmer, which takes in a format string and pointers to variables in which the data that needs to be printed is stored.

#include <time.h>
#include <stdio.h>
int main()
{
struct timespec time;
time.tv_sec = 56;
time.tv_nsec = 100;
printf("%lld.%.9ld seconds have elapsed!", (long long) time.tv_sec, time.tv_nsec);
printf("\nOR \n%d seconds and %ld nanoseconds have elapsed!", time.tv_sec, time.tv_nsec);
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved