5

I am trying to obtain the CPU time consumed by a process on Ubuntu. As far as I know, there are two functions can do this job: getrusage() and clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp). In my code, calling getrusage() immediately after clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp), always gives different results.

Can anyone please help me understand which function gives higher resolution, and what advantages/disadvantages of these functions have?

Thanks.

Dillon Geo
  • 271
  • 1
  • 2
  • 6

1 Answers1

0

getrusage(...)

  • Splits CPU time into system and user components in ru_utime and ru_stime respectively.
  • Roughly microsecond resolution: struct timeval has the field tv_usec, but this resolution is usually limited to about 4ms/250Hz (source)
  • Available on SVr4, 4.3BSD, POSIX.1-2001: this means it is available on both Linux and OS X

See the man page


clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...)

  • Combined total of system and user time with no way to separate it into system/user time components.
  • Nanosecond resolution: struct timespec is a clone of struct timeval but with tv_nsec instead of tv_usec. Exact resolution depends on how the timer is implemented on given system, and can be queried with clock_getres.
  • Requires you to link to librt
  • Clock may not be available. In this case, clock_gettime will return -1 and set errno to EINVAL, so it's a good idea to provide a getrusage fallback. (source)
  • Available on SUSv2 and POSIX.1-2001: this means it is available on Linux, but not OS X.

See the man page

Cameron
  • 1,017
  • 2
  • 10
  • 18