1CLOCK_GETRES(2)            Linux Programmer's Manual           CLOCK_GETRES(2)
2
3
4

NAME

6       clock_getres, clock_gettime, clock_settime - clock and time functions
7

SYNOPSIS

9       #include <time.h>
10
11       int clock_getres(clockid_t clockid, struct timespec *res);
12
13       int clock_gettime(clockid_t clockid, struct timespec *tp);
14       int clock_settime(clockid_t clockid, const struct timespec *tp);
15
16       Link with -lrt (only for glibc versions before 2.17).
17
18   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
19
20       clock_getres(), clock_gettime(), clock_settime():
21           _POSIX_C_SOURCE >= 199309L
22

DESCRIPTION

24       The  function  clock_getres()  finds  the resolution (precision) of the
25       specified clock clockid, and, if res is  non-NULL,  stores  it  in  the
26       struct timespec pointed to by res.  The resolution of clocks depends on
27       the implementation and cannot be configured by  a  particular  process.
28       If  the  time value pointed to by the argument tp of clock_settime() is
29       not a multiple of res, then it is truncated to a multiple of res.
30
31       The functions clock_gettime() and clock_settime() retrieve and set  the
32       time of the specified clock clockid.
33
34       The  res  and  tp  arguments  are  timespec structures, as specified in
35       <time.h>:
36
37           struct timespec {
38               time_t   tv_sec;        /* seconds */
39               long     tv_nsec;       /* nanoseconds */
40           };
41
42       The clockid argument is the identifier of the particular clock on which
43       to  act.   A  clock  may  be system-wide and hence visible for all pro‐
44       cesses, or per-process  if  it  measures  time  only  within  a  single
45       process.
46
47       All  implementations  support the system-wide real-time clock, which is
48       identified by CLOCK_REALTIME.  Its time represents seconds and nanosec‐
49       onds  since the Epoch.  When its time is changed, timers for a relative
50       interval are unaffected, but timers for an absolute point in  time  are
51       affected.
52
53       More  clocks may be implemented.  The interpretation of the correspond‐
54       ing time values and the effect on timers is unspecified.
55
56       Sufficiently recent versions of glibc and the Linux kernel support  the
57       following clocks:
58
59       CLOCK_REALTIME
60              A  settable  system-wide  clock  that measures real (i.e., wall-
61              clock) time.  Setting this  clock  requires  appropriate  privi‐
62              leges.   This  clock  is  affected by discontinuous jumps in the
63              system time (e.g., if the system administrator manually  changes
64              the clock), and by the incremental adjustments performed by adj‐
65              time(3) and NTP.
66
67       CLOCK_REALTIME_ALARM (since Linux 3.0; Linux-specific)
68              Like CLOCK_REALTIME, but not settable.  See timer_create(2)  for
69              further details.
70
71       CLOCK_REALTIME_COARSE (since Linux 2.6.32; Linux-specific)
72              A faster but less precise version of CLOCK_REALTIME.  This clock
73              is not settable.  Use when you need very  fast,  but  not  fine-
74              grained  timestamps.   Requires  per-architecture  support,  and
75              probably also architecture support for this flag in the vdso(7).
76
77       CLOCK_TAI (since Linux 3.10; Linux-specific)
78              A nonsettable system-wide clock derived from wall-clock time but
79              ignoring leap seconds.  This clock does not experience disconti‐
80              nuities and backwards jumps caused by NTP inserting leap seconds
81              as CLOCK_REALTIME does.
82
83              The acronym TAI refers to International Atomic Time.
84
85       CLOCK_MONOTONIC
86              A  nonsettable  system-wide clock that represents monotonic time
87              since—as described  by  POSIX—"some  unspecified  point  in  the
88              past".   On  Linux, that point corresponds to the number of sec‐
89              onds that the system has been running since it was booted.
90
91              The CLOCK_MONOTONIC clock is not affected by discontinuous jumps
92              in  the  system time (e.g., if the system administrator manually
93              changes the clock), but is affected by the  incremental  adjust‐
94              ments  performed  by  adjtime(3)  and  NTP.  This clock does not
95              count time that the system is  suspended.   All  CLOCK_MONOTONIC
96              variants  guarantee  that the time returned by consecutive calls
97              will not go backwards, but successive calls may—depending on the
98              architecture—return identical (not-increased) time values.
99
100       CLOCK_MONOTONIC_COARSE (since Linux 2.6.32; Linux-specific)
101              A  faster but less precise version of CLOCK_MONOTONIC.  Use when
102              you need very fast, but not fine-grained  timestamps.   Requires
103              per-architecture support, and probably also architecture support
104              for this flag in the vdso(7).
105
106       CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)
107              Similar to CLOCK_MONOTONIC, but provides access to a  raw  hard‐
108              ware-based  time  that  is not subject to NTP adjustments or the
109              incremental adjustments performed  by  adjtime(3).   This  clock
110              does not count time that the system is suspended.
111
112       CLOCK_BOOTTIME (since Linux 2.6.39; Linux-specific)
113              A nonsettable system-wide clock that is identical to CLOCK_MONO‐
114              TONIC, except that it also includes any time that the system  is
115              suspended.   This  allows  applications  to  get a suspend-aware
116              monotonic clock without having to deal with the complications of
117              CLOCK_REALTIME,  which  may  have discontinuities if the time is
118              changed using settimeofday(2) or similar.
119
120       CLOCK_BOOTTIME_ALARM (since Linux 3.0; Linux-specific)
121              Like CLOCK_BOOTTIME.  See timer_create(2) for further details.
122
123       CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
124              This is a clock that measures CPU time consumed by this  process
125              (i.e.,  CPU  time  consumed  by all threads in the process).  On
126              Linux, this clock is not settable.
127
128       CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12)
129              This is a clock that measures CPU time consumed by this  thread.
130              On Linux, this clock is not settable.
131
132       Linux also implements dynamic clock instances as described below.
133
134   Dynamic clocks
135       In addition to the hard-coded System-V style clock IDs described above,
136       Linux also supports POSIX clock operations  on  certain  character  de‐
137       vices.   Such  devices  are  called "dynamic" clocks, and are supported
138       since Linux 2.6.39.
139
140       Using the appropriate macros, open file descriptors  may  be  converted
141       into  clock  IDs  and  passed  to clock_gettime(), clock_settime(), and
142       clock_adjtime(2).  The following example shows how to  convert  a  file
143       descriptor into a dynamic clock ID.
144
145           #define CLOCKFD 3
146           #define FD_TO_CLOCKID(fd)   ((~(clockid_t) (fd) << 3) | CLOCKFD)
147           #define CLOCKID_TO_FD(clk)  ((unsigned int) ~((clk) >> 3))
148
149           struct timespec ts;
150           clockid_t clkid;
151           int fd;
152
153           fd = open("/dev/ptp0", O_RDWR);
154           clkid = FD_TO_CLOCKID(fd);
155           clock_gettime(clkid, &ts);
156

RETURN VALUE

158       clock_gettime(),  clock_settime(), and clock_getres() return 0 for suc‐
159       cess.  On error, -1 is returned and errno is set to indicate the error.
160

ERRORS

162       EACCES clock_settime() does not have write permission for  the  dynamic
163              POSIX clock device indicated.
164
165       EFAULT tp points outside the accessible address space.
166
167       EINVAL The clockid specified is invalid for one of two reasons.  Either
168              the System-V style hard coded positive value is out of range, or
169              the  dynamic  clock  ID  does not refer to a valid instance of a
170              clock object.
171
172       EINVAL (clock_settime()): tp.tv_sec is negative or tp.tv_nsec  is  out‐
173              side the range [0..999,999,999].
174
175       EINVAL The clockid specified in a call to clock_settime() is not a set‐
176              table clock.
177
178       EINVAL (since Linux 4.3)
179              A call to clock_settime() with a clockid of  CLOCK_REALTIME  at‐
180              tempted  to  set the time to a value less than the current value
181              of the CLOCK_MONOTONIC clock.
182
183       ENODEV The hot-pluggable device (like USB for example) represented by a
184              dynamic  clk_id  has  disappeared after its character device was
185              opened.
186
187       ENOTSUP
188              The operation is not supported by the dynamic POSIX clock device
189              specified.
190
191       EPERM  clock_settime()  does not have permission to set the clock indi‐
192              cated.
193

VERSIONS

195       These system calls first appeared in Linux 2.6.
196

ATTRIBUTES

198       For an  explanation  of  the  terms  used  in  this  section,  see  at‐
199       tributes(7).
200
201       ┌────────────────────────────────────────────┬───────────────┬─────────┐
202Interface                                   Attribute     Value   
203       ├────────────────────────────────────────────┼───────────────┼─────────┤
204clock_getres(), clock_gettime(),            │ Thread safety │ MT-Safe │
205clock_settime()                             │               │         │
206       └────────────────────────────────────────────┴───────────────┴─────────┘
207

CONFORMING TO

209       POSIX.1-2001, POSIX.1-2008, SUSv2.
210
211       On POSIX systems on which these functions  are  available,  the  symbol
212       _POSIX_TIMERS  is defined in <unistd.h> to a value greater than 0.  The
213       symbols _POSIX_MONOTONIC_CLOCK,  _POSIX_CPUTIME,  _POSIX_THREAD_CPUTIME
214       indicate      that      CLOCK_MONOTONIC,      CLOCK_PROCESS_CPUTIME_ID,
215       CLOCK_THREAD_CPUTIME_ID are available.  (See also sysconf(3).)
216

NOTES

218       POSIX.1 specifies the following:
219
220              Setting the value of the  CLOCK_REALTIME  clock  via  clock_set‐
221              time()  shall have no effect on threads that are blocked waiting
222              for a relative time service based upon this clock, including the
223              nanosleep()  function;  nor on the expiration of relative timers
224              based upon this clock.  Consequently, these time services  shall
225              expire  when  the  requested relative interval elapses, indepen‐
226              dently of the new or old value of the clock.
227
228       According to POSIX.1-2001, a process with "appropriate privileges"  may
229       set the CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID clocks us‐
230       ing clock_settime().  On Linux, these clocks are not settable (i.e., no
231       process has "appropriate privileges").
232
233   C library/kernel differences
234       On some architectures, an implementation of clock_gettime() is provided
235       in the vdso(7).
236
237   Historical note for SMP systems
238       Before Linux added  kernel  support  for  CLOCK_PROCESS_CPUTIME_ID  and
239       CLOCK_THREAD_CPUTIME_ID,  glibc  implemented these clocks on many plat‐
240       forms using timer registers from the CPUs (TSC on i386, AR.ITC on  Ita‐
241       nium).   These  registers  may differ between CPUs and as a consequence
242       these clocks may return bogus results if a process is migrated  to  an‐
243       other CPU.
244
245       If  the  CPUs in an SMP system have different clock sources, then there
246       is no way to maintain a correlation between the timer  registers  since
247       each  CPU  will  run at a slightly different frequency.  If that is the
248       case, then clock_getcpuclockid(0) will return ENOENT  to  signify  this
249       condition.   The  two  clocks will then be useful only if it can be en‐
250       sured that a process stays on a certain CPU.
251
252       The processors in an SMP system do not start all at  exactly  the  same
253       time and therefore the timer registers are typically running at an off‐
254       set.  Some architectures include code that attempts to limit these off‐
255       sets  on bootup.  However, the code cannot guarantee to accurately tune
256       the offsets.  Glibc contains no provisions to deal with  these  offsets
257       (unlike  the  Linux  Kernel).   Typically  these  offsets are small and
258       therefore the effects may be negligible in most cases.
259
260       Since glibc 2.4, the wrapper functions for the system  calls  described
261       in  this page avoid the abovementioned problems by employing the kernel
262       implementation of CLOCK_PROCESS_CPUTIME_ID and CLOCK_THREAD_CPUTIME_ID,
263       on  systems that provide such an implementation (i.e., Linux 2.6.12 and
264       later).
265

EXAMPLES

267       The program below demonstrates the use of clock_gettime() and clock_ge‐
268       tres()  with  various  clocks.  This is an example of what we might see
269       when running the program:
270
271           $ ./clock_times x
272           CLOCK_REALTIME : 1585985459.446 (18356 days +  7h 30m 59s)
273                resolution:          0.000000001
274           CLOCK_TAI      : 1585985496.447 (18356 days +  7h 31m 36s)
275                resolution:          0.000000001
276           CLOCK_MONOTONIC:      52395.722 (14h 33m 15s)
277                resolution:          0.000000001
278           CLOCK_BOOTTIME :      72691.019 (20h 11m 31s)
279                resolution:          0.000000001
280
281   Program source
282
283       /* clock_times.c
284
285          Licensed under GNU General Public License v2 or later.
286       */
287       #define _XOPEN_SOURCE 600
288       #include <time.h>
289       #include <stdint.h>
290       #include <stdio.h>
291       #include <stdlib.h>
292       #include <stdbool.h>
293       #include <unistd.h>
294
295       #define SECS_IN_DAY (24 * 60 * 60)
296
297       static void
298       displayClock(clockid_t clock, const char *name, bool showRes)
299       {
300           struct timespec ts;
301
302           if (clock_gettime(clock, &ts) == -1) {
303               perror("clock_gettime");
304               exit(EXIT_FAILURE);
305           }
306
307           printf("%-15s: %10jd.%03ld (", name,
308                   (intmax_t) ts.tv_sec, ts.tv_nsec / 1000000);
309
310           long days = ts.tv_sec / SECS_IN_DAY;
311           if (days > 0)
312               printf("%ld days + ", days);
313
314           printf("%2dh %2dm %2ds",
315                   (int) (ts.tv_sec % SECS_IN_DAY) / 3600,
316                   (int) (ts.tv_sec % 3600) / 60,
317                   (int) ts.tv_sec % 60);
318           printf(")\n");
319
320           if (clock_getres(clock, &ts) == -1) {
321               perror("clock_getres");
322               exit(EXIT_FAILURE);
323           }
324
325           if (showRes)
326               printf("     resolution: %10jd.%09ld\n",
327                       (intmax_t) ts.tv_sec, ts.tv_nsec);
328       }
329
330       int
331       main(int argc, char *argv[])
332       {
333           bool showRes = argc > 1;
334
335           displayClock(CLOCK_REALTIME, "CLOCK_REALTIME", showRes);
336       #ifdef CLOCK_TAI
337           displayClock(CLOCK_TAI, "CLOCK_TAI", showRes);
338       #endif
339           displayClock(CLOCK_MONOTONIC, "CLOCK_MONOTONIC", showRes);
340       #ifdef CLOCK_BOOTTIME
341           displayClock(CLOCK_BOOTTIME, "CLOCK_BOOTTIME", showRes);
342       #endif
343           exit(EXIT_SUCCESS);
344       }
345

SEE ALSO

347       date(1),   gettimeofday(2),   settimeofday(2),   time(2),   adjtime(3),
348       clock_getcpuclockid(3),  ctime(3),  ftime(3), pthread_getcpuclockid(3),
349       sysconf(3), time(7), time_namespaces(7), vdso(7), hwclock(8)
350

COLOPHON

352       This page is part of release 5.13 of the Linux  man-pages  project.   A
353       description  of  the project, information about reporting bugs, and the
354       latest    version    of    this    page,    can     be     found     at
355       https://www.kernel.org/doc/man-pages/.
356
357
358
359                                  2021-03-22                   CLOCK_GETRES(2)
Impressum