Volodymyr
Volodymyr

Reputation: 1587

Unix process' CPU usage

I need to determeni the unix process' CPU usage... So, i want to write a bash script which will enable timer, run some process, stop timer. And I must know how that process used the CPU. And then compare with another process - which of them uses CPU less. Tried this thread, but is uses c++, I would like to do that in bash. Thanks.

Upvotes: 1

Views: 726

Answers (1)

John1024
John1024

Reputation: 113814

You want to "enable timer, run some process, stop timer." Bash provides a builtin command to time processes, conveniently called time. To find, for example, how long it takes the date command to run:

$ time date
Mon Dec 30 12:16:22 PST 2013

real    0m0.003s
user    0m0.000s
sys     0m0.004s

The first line of output above is the result of the date command. The last three are from time telling you how long the date command took to run (real) and the CPU time spent in user mode and system mode.

time will optionally also display the CPU usage which is computed as the sum of user and system time divided by real time. With the following environment variable TIMEFORMAT, we obtain output that looks like the default except for the addition of one line showing CPU usage in percent:

$ TIMEFORMAT=$'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS\nCPU\t%P%%'
$ time sleep 1

real    0m1.003s
user    0m0.000s
sys     0m0.000s
CPU     0.00%

The string is in the $'...' format so that \n is interpreted as a newline and \t as a tab. If one does not want newlines and tabs, then `$'...' would not be needed. For example, the following would produce the same information but on one line:

TIMEFORMAT='real=%R  user=%U sys=%S CPU=%P%%'

In the above TIMEFORMAT specifications, %P provides the CPU usage in percent. For illustration, I also simplified the last spec above by dropping the "3" and "l" options; as a result time is displayed in default precision and in seconds rather than the longer minutes and seconds form. See the description of the TIMEFORMAT environment variable in man bash for more information.

Upvotes: 7

Related Questions