3

I am trying to understand how cpu time is computed in Linux. In particular, I would like to focus in this question on clock_gettime and on getrusage. I'm wondering how are these two related.

  • Does one call the other one?
  • Do they both rely on the same underlying mechanism?
  • If so what's their greatest common denominator, and by that I mean, what function from the linux kernel are they both calling to get the time?
  • And if they are not relying on the same underlying mechanism then why?
Vincent
  • 57,703
  • 61
  • 205
  • 388

1 Answers1

1

There are lots of clocks in Unix and Linux. Some are wall clocks (CLOCK_REALTIME), some are modified wall clocks (CLOCK_MONO, CLOCK_BOOT), and some are CPU time clocks (CLOCK_PROCESS_CPUTIME_ID, CLOCK_THREAD_CPUTIME_ID).

clock_gettime can pull from basically any clock that has a clkid assigned. (Down in the kernel, there's basically code that, for each clkid, defines an appropriate get method for clock_gettime to use.)

I suspect, but have not confirmed, that clock_gettime with one of the CPU-time-related clkids pulls from the same CPU counters as getrusage does.

Answering your questions in turn:

Does one call the other one?

I don't believe so.

Do they both rely on the same underlying mechanism?

I believe so, but I have not confirmed this.

If so what's their greatest common denominator, and by that I mean, what function from the linux kernel are they both calling to get the time?

I'm not sure. (Sorry. My work in all of this has been focused on the wall times, not the CPU times.)

And if they are not relying on the same underlying mechanism then why?

Because the time-related code in the Linux kernel is crazy complicated, and tries to serve a lot of different masters.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103