Skip to content
Tutorials Center
My learning

Topics

C Reference ยท ctype.h, math.h and others

C timespec_get() and clock_gettime() functions

Reference for timespec_get() (C11) and POSIX clock_gettime(): nanosecond timestamps, monotonic clocks for timing code, and nanosleep, with examples.

Both timespec_get() (C11) and clock_gettime() (POSIX) fill a struct timespec: whole seconds in tv_sec and nanoseconds in tv_nsec. That gives far better resolution than time(), which only counts seconds.

Which function to use depends on what you need. timespec_get(&ts, TIME_UTC) gives the current wall-clock time and is plain ISO C. clock_gettime(CLOCK_MONOTONIC, &ts) gives a clock that never jumps backward, which makes it the right choice for measuring how long something took. clock_gettime(CLOCK_REALTIME, ...) is the POSIX spelling of wall-clock time.

C
#define _POSIX_C_SOURCE 200809L
#include <time.h>

struct timespec t0, t1;
clock_gettime(CLOCK_MONOTONIC, &t0);
/* ... work ... */
clock_gettime(CLOCK_MONOTONIC, &t1);

Try it

C timespec_get: the C11 wall clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C clock_gettime: timing with a monotonic clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
struct timespec { time_t tv_sec; long tv_nsec; };

int timespec_get(struct timespec *ts, int base);                 /* C11 */
int clock_gettime(clockid_t clk_id, struct timespec *tp);        /* POSIX */
int clock_getres(clockid_t clk_id, struct timespec *res);        /* POSIX */
int nanosleep(const struct timespec *req, struct timespec *rem); /* POSIX */
Name Description
ts, tp, res Output struct timespec.
base Time base for timespec_get; the only one required by C is TIME_UTC.
clk_id Which clock: see the table below.
req, rem For nanosleep: how long to sleep, and the remaining time if a signal interrupted the sleep (may be NULL).
Clock Meaning
CLOCK_REALTIME Wall-clock time since the epoch. Can jump when an administrator or NTP adjusts the clock.
CLOCK_MONOTONIC Time since an unspecified starting point that only moves forward. Use for intervals.
CLOCK_PROCESS_CPUTIME_ID CPU time consumed by the process (all threads).
CLOCK_THREAD_CPUTIME_ID CPU time consumed by the calling thread.

Returns: timespec_get() returns base (nonzero) on success and 0 on failure. clock_gettime(), clock_getres() and nanosleep() return 0 on success and -1 on failure, setting errno (for nanosleep, EINTR when interrupted).

Errors / undefined behavior: an unsupported base or clock makes the call fail with the values above; a bad pointer is undefined behavior. C23 adds timespec_getres(), which the runner's C library does not provide.

Usage notes

  • Measure durations with CLOCK_MONOTONIC, never with time() or CLOCK_REALTIME: those can step backward during clock adjustments and produce negative or huge intervals.
  • Subtract carefully. Compute (sec2 - sec1) * 1e9 + (nsec2 - nsec1); tv_nsec alone can be smaller in the later sample, giving a negative term that is still correct once the seconds are added. Use long long for the nanosecond total to avoid overflow on 32-bit long.
  • Resolution is not accuracy. The fields have nanosecond units, but the actual clock tick may be coarser; clock_getres() tells you. Timing a few nanoseconds of work needs many iterations.
  • CLOCK_REALTIME and timespec_get(TIME_UTC) are essentially the same clock on Linux. If the system has no clock, timespec_get() fails and returns 0.
  • The sleep is a lower bound. nanosleep() may sleep a little longer because of scheduling, and shorter only when interrupted by a signal; loop with rem if you must complete the full delay.
  • Windows: timespec_get works in current MSVC; use QueryPerformanceCounter for intervals there since clock_gettime is not available. macOS has clock_gettime since 10.12.
  • CLOCK_PROCESS_CPUTIME_ID is the precise version of clock().
  • In tests, never assert exact elapsed times. Check lower bounds and generous upper bounds, as the example does.
  • Standard version: timespec_get is C11; clock_gettime, clock_getres and nanosleep are POSIX.1-2001 (_POSIX_C_SOURCE 199309L or later).