Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android(Linux) uptime using CLOCK_MONOTONIC

According to Android Developer Reference uptimeMillis() returns the number of milliseconds since boot, not counting time spent in deep sleep. I checked the implementation of uptimeMillis() in my code and it is roughly like this-

struct timespec t;
t.tv_sec = t.tv_nsec = 0;
clock_gettime(CLOCK_MONOTONIC, &t);
return (int64_t)(t.tv_sec)*1000000000LL + t.tv_nsec;

As far as I know CLOCK_MONOTONIC counts from some unspecified point linearly including sleep time.

Here are my doubts-

  1. If CLOCK_MONOTONIC includes sleep time, how come uptimeMillis() doesn't take it into account? If my understanding is wrong and CLOCK_MONOTONIC doesn't take sleep into account, then what should I use to get system uptime including sleep?

  2. What is deep sleep? Is the CPU idling referred as deep sleep?

  3. What is the value of unspecified point in Linux? Can you kindly point out in code where this clock is started?

like image 750
Pavan Manjunath Avatar asked Jun 15 '11 15:06

Pavan Manjunath


1 Answers

  1. CLOCK_MONOTONIC stops when the system is suspended. Some people felt this was a mistake, and subsequently there have been patches for adding a CLOCK_BOOTTIME clock: https://lwn.net/Articles/428176/ . I don't know if these patches have yet been included in the mainline kernel. CLOCK_BOOTTIME is in ndk-9c - it only took 2,5 years ;) – Wojciech

  2. Suspend, I guess.

  3. IIRC some fixed time before boot. You'll find the exact value if you dig into the kernel source. Then again, the entire point about it being unspecified is that it could change at any point, so relying on it seems unwise to me.

like image 200
janneb Avatar answered Oct 03 '22 23:10

janneb