Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is CLOCK_MONOTONIC process (or thread) specific?

If I get the time using clock_gettime(CLOCK_MONOTONIC,x), then call yield (e.g. sched_yield()), then get the CLOCK_MONOTONIC time again, will the difference in times include the time the program wasn't running (having yielded), or does CLOCK_MONOTONIC only track the time during which the program is executing? My tests seem to imply the latter, but I'd like to know for sure.

Also, if CLOCK_MONOTONIC doesn't include the time yielded, is there another monotonic timer (ie. one not subject to jumps caused by ntp) that does?

like image 226
Benubird Avatar asked Feb 09 '11 10:02

Benubird


2 Answers

The answer Maxim and comments to that answered the second part of your question, I believe. To expand on the answer for the first part, POSIX 2008 states

If the Monotonic Clock option is supported, all implementations shall support a clock_id of CLOCK_MONOTONIC defined in <time.h>. This clock represents the monotonic clock for the system. For this clock, the value returned by clock_gettime() represents the amount of time (in seconds and nanoseconds) since an unspecified point in the past (for example, system start-up time, or the Epoch). This point does not change after system start-up time.

In particular, note "the monotonic clock for the system". That is, per-system and not per-process, it keeps ticking even though your process is not running. Also, "This point does not change after system start-up time.", which again implies that it keeps ticking regardless of whether a particular process is running or sleeping.

So, either you have found a bug in the Linux implementation, or more likely, in your test program.

like image 117
janneb Avatar answered Sep 20 '22 23:09

janneb


The only difference between CLOCK_REALTIME and CLOCK_MONOTONIC is that the latter can not be set. These clocks are ticking even when your process is not running.

http://www.opengroup.org/onlinepubs/009604599/functions/clock_getres.html

Note that the absolute value of the monotonic clock is meaningless (because its origin is arbitrary), and thus there is no need to set it. Furthermore, realtime applications can rely on the fact that the value of this clock is never set and, therefore, that time intervals measured with this clock will not be affected by calls to clock_settime().

In Linux, surprisingly, CLOCK_MONOTONIC seems to be still affected by NTP adjustments, so that it could go backwards. Hence they added another clock CLOCK_MONOTONIC_RAW:

man clock_gettime

CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific) Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments.

like image 21
Maxim Egorushkin Avatar answered Sep 20 '22 23:09

Maxim Egorushkin