4.7. Using _COARSE POSIX Clocks for Application Timestamping
clock_gettime()
function to produce clock readings with the lowest cost possible.
POSIX clocks is a standard for implementing and representing time sources. The POSIX clocks can be selected by each application, without affecting other applications in the system. This is in contrast to the hardware clocks as described in Section 2.6, “Using Hardware Clocks for System Timestamping”, which is selected by the kernel and implemented across the system.
clock_gettime()
, which is defined at <time.h>
. clock_gettime()
has a counterpart in the kernel, in the form of a system call. When the user process calls clock_gettime()
, the corresponding C library (glibc
) calls the sys_clock_gettime()
system call which performs the requested operation and then returns the result to the user program.
CLOCK_MONOTONIC_COARSE
and CLOCK_REALTIME_COARSE
POSIX clocks was created in the form of a VDSO library function.
clock_gettime()
, using one of the _COARSE
clock variants, do not require kernel intervention and are executed entirely in user space, which yields a significant performance gain. Time readings for _COARSE
clocks have a millisecond (ms) resolution, meaning that time intervals smaller than 1ms will not be recorded. The _COARSE
variants of the POSIX clocks are suitable for any application that can accommodate millisecond clock resolution, and the benefits are more evident on systems which use hardware clocks with high reading costs.
Note
_COARSE
prefix, see the Red Hat Enterprise Linux for Real Time Reference guide for Red Hat Enterprise Linux for Real Time.
Example 4.1. Using the _COARSE
Clock Variant in clock_gettime
#include <time.h> main() { int rc; long i; struct timespec ts; for(i=0; i<10000000; i++) { rc = clock_gettime(CLOCK_MONOTONIC_COARSE, &ts); } }
clock_gettime()
, to verify the value of the rc
variable, or to ensure the content of the ts
structure is to be trusted. The clock_gettime()
manpage provides more information to help you write more reliable applications.
Important
clock_gettime()
function must be linked with the rt
library by adding '-lrt'
to the gcc
command line.
~]$ gcc clock_timing.c -o clock_timing -lrt
For more information, or for further reading, the following man page and books are related to the information given in this section.
- clock_gettime()
- Linux System Programming by Robert Love
- Understanding The Linux Kernel by Daniel P. Bovet and Marco Cesati