Bash – Format the output of cputime for ps

bashpstext formatting

I'm trying to write a script that can monitor a process's CPU usage over an interval (to create a graph).

So far, this is the command I'm using

ps -p $PROCID -o cputime,etimes

My only concern is that the output of cputime appears to be [dd]hh:mm (or something similar, can't remember off the top of my head now)

Is there a way to format cputime in seconds, kind of like etime -> etimes to get elapsed time in seconds?

Edit: This is the output that I'm currently receiving

2-03:01:33 2653793

I'd like the first parameter to be formatted in seconds, not days-hours:minutes:seconds.

Best Answer

This converts the first time to seconds:

ps -p $PROCID -o cputime,etimes | awk -F'[: ]+' '/:/ {t=$3+60*($2+60*$1); print t,$NF}'

As an example, the ps command produces:

$ ps -p 5403 -o cputime,etimes
    TIME ELAPSED
01:33:38 1128931

The awk command processes that and returns:

ps -p 5403 -o cputime,etimes | awk -F'[: ]+' '/:/ {t=$3+60*($2+60*$1); print t,$NF}'
5618 1128931

Explanation

  • -F'[: ]+'

    This tells awk to treat both colons and spaces as field separators. This way, the hours, minutes, and seconds appear as separate fields.

  • /:/ {t=$3+60*($2+60*$1); print t,$NF}

    The initial /:/ restricts the code to working only on lines that include a colon. This removes the header lines. The number of seconds is calculated from hours, minutes, seconds via t=$3+60*($2+60*$1). The resulting value for t is then printed along side with the elapsed time.

Handling days

If ps produces days,hours,minutes,seconds, as in:

2-03:01:33

Then, use this code instead:

ps -p $PROCID -o cputime,etimes | awk -F'[-: ]+' '/:/ {t=$4+60*($3+60*($2+24*$1)); print t,$NF}'

If days may or may not be prepended to the output, then use this combination command:

ps -p $PROCID -o cputime,etimes | awk -F'[-: ]+' '/:/ && NF==5 { t=$4+60*($3+60*($2+24*$1)); print t,$NF} /:/ && NF==4 {t=$3+60*($2+60*$1); print t,$NF}'
Related Question