process time – Obtain User and Kernel Time of a Running Process

processtime

Is there way to determine using standard Linux/Unix tools how much a process has spent in User mode and how much waiting for kernel?

In other words, exactly the "user" and "sys" values that you get when using time, but during process runtime?

NOTE: one way is to use WBEM and enumerate Linux_UnixProcess, but I need to use other tool than this; my aim is to verify what WBEM provider tells me, i.e. I need to use different tool.

Best Answer

On Linux, the info is available in fields 14 to 17 of /proc/$pid/stat (see proc(5) for details):

Fields are:

  • 14: user time (in number of clock ticks)
  • 15: sys time
  • 16: user time of waited for children
  • 17: sys time of waited for children

(all the threads of a given process have the same values there)

They are not directly reported by ps.

ps reports 14 + 15 with ps -o time and 14 + 15 + 16 + 17 with ps --cumulative -o bsdtime.

Beware that the second field in /proc/$pid/stat may contain spaces or newline characters, so you can't parse it with awk's $1, $2...

You can use perl like:

$ perl -MPOSIX -l -0777 -ne '@f = /\(.*\)|\S+/gs;
    printf "utime: %.2f\nstime: %.2f\ncutime: %.2f\ncstime: %.2f\n",
      map {$_/POSIX::sysconf( &POSIX::_SC_CLK_TCK )}@f[13..16]' "/proc/$pid/stat"
utime: 3.79
stime: 2.06
cutime: 56.49
cstime: 34.27

A process can retrieve its own times with getrusage(RUSAGE_SELF) and getrusage(RUSAGE_CHILDREN).

There's also a times system call that retrieves the same information. POSIX shells have a times builtin for that. Some shells also provide with that information with time (without arguments).

$ times
0m3.800s 0m2.060s
0m56.512s 0m34.276s

$ ps -o time -p "$$"
    TIME
00:00:05
$ ps --cumulative -o bsdtime -p "$$"
  TIME
  1:36