1

I'd like to use bash's builtin time command to measure the remaining cpu/user time used up by a program that is already executing.

More precisely, I would like to write a bash script that, given a process id, will print the cpu time used by that process between the time when the script was started and the time when the process exits. The output should be produced right after the process exits.

4
  • What do you mean by remaining? You mean how much more time a process will need? That won't be possible since there's no way to guess. What if the thing you are running has a command to wait for 24 hours before finishing?
    – terdon
    Commented Jul 6, 2019 at 13:54
  • No, what I want to do is e.g. start a bash script, pass it the PID of some running process as an argument and then have the script print the cpu time that process has used between the point in time when the script was started and when the process has finished (obviously after the latter has occurred).
    – Peter
    Commented Jul 6, 2019 at 13:57
  • Please edit your question and clarify then. So you want the bash script to wait until the running process has finished and then print the time it took? And you want cpu/user time, not actual wall clock time, right?
    – terdon
    Commented Jul 6, 2019 at 13:59
  • Done, yes I want cpu time that's why I'm unsure how to do this.
    – Peter
    Commented Jul 6, 2019 at 14:04

1 Answer 1

2

I don't know how you can be told anything about a process that has already exited (unless there is an audit capability somewhere).

In a plain Unix, I would run

ps --pid $pid -o cputime=

repeatedly until I get rc<>0, in which case the used CPU would be very close to what the last reading was.

The "=" at the end of cputime= suppresses columns headers.

2
  • This seems to work, only downside is that the granularity is in seconds. But this makes me think there should be a way to get more accurate readings (from C code if necessary). I'll accept this anyways since I did not specify what precision I wanted to achieve and this answers the question as it is.
    – Peter
    Commented Jul 7, 2019 at 8:16
  • @peter You can get better than a second, the sleep command accepts fractional seconds (sleep .2).
    – xenoid
    Commented Jul 7, 2019 at 10:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .