I am trying to obtain the CPU time consumed by a process on Ubuntu. As far as I know, there are two functions can 开发者_如何学Cdo 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.
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
精彩评论