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.
#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
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.
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
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 withtime()orCLOCK_REALTIME: those can step backward during clock adjustments and produce negative or huge intervals. - Subtract carefully. Compute
(sec2 - sec1) * 1e9 + (nsec2 - nsec1);tv_nsecalone can be smaller in the later sample, giving a negative term that is still correct once the seconds are added. Uselong longfor the nanosecond total to avoid overflow on 32-bitlong. - 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_REALTIMEandtimespec_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 withremif you must complete the full delay. - Windows:
timespec_getworks in current MSVC; useQueryPerformanceCounterfor intervals there sinceclock_gettimeis not available. macOS hasclock_gettimesince 10.12. CLOCK_PROCESS_CPUTIME_IDis the precise version ofclock().- In tests, never assert exact elapsed times. Check lower bounds and generous upper bounds, as the example does.
- Standard version:
timespec_getis C11;clock_gettime,clock_getresandnanosleepare POSIX.1-2001 (_POSIX_C_SOURCE 199309Lor later).