2

I have a bash script which runs a series of programs which run other programs . How would I get the cpu time of the bash script and all of it descendants processes.

I looked in /proc/{process-id}/stat and the question How to calculate the CPU usage of a process by PID in Linux from C?

but I am not sure how I would calculate the total cpu time for all the child processes of the bash script.

Edit If I calculate difference in utime and difference in stime for some time interval, I know for a single process the cpu time (utime + stime) it took in that interval.

How would I add up the cpu time for all the child processes (which also create their own processes) while the process is still running?

Community
  • 1
  • 1
Bilal Syed Hussain
  • 8,664
  • 11
  • 38
  • 44

1 Answers1

2

You can calculate it using the:

utime %lu

Amount of time that this process has been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK). This includes guest time, guest_time (time spent running a virtual CPU, see below), so that applications that are not aware of the guest time field do not lose that time from their calculations.

stime %lu

Amount of time that this process has been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK).

cutime %ld

Amount of time that this process's waited-for children have been scheduled in user mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK). (See also times(2).) This includes guest time, cguest_time (time spent running a virtual CPU, see below).

cstime %ld

Amount of time that this process's waited-for children have been scheduled in kernel mode, measured in clock ticks (divide by sysconf(_SC_CLK_TCK).

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • These times don't seems to include the cpu of the children, e.g if the bash script run another script which ran java looking at /proc/{bash-script-process-id}/stat does seem to include the cpu time of the java process, how would get the cpu time of all the children? – Bilal Syed Hussain Dec 10 '13 at 15:48
  • You mention several times to see below, are you referring to cstime? – jfa Dec 10 '13 at 15:50
  • On the top level script the utime, cutime, stime are 0 whereas the the utime and stime of the child java process are 29007 and 192, and the child java process's cstime is 0. The process is still running – Bilal Syed Hussain Dec 10 '13 at 15:55
  • @Bilal were you able to find some way eventually? – pranavk Mar 10 '16 at 10:31
  • @pranavk I wrote a C program that looked into /proc and added the cpu time of the program and it subprocess – Bilal Syed Hussain Mar 10 '16 at 13:35
  • Yeah, that is what came to my mind too, but I was wondering if there is any inbuilt way to find it for a process + its children in one shot just like it is already there for process + terminated children. Anyways, I will go this way then. – pranavk Mar 10 '16 at 13:37