Skip to content
Advertisement

How to get CPU Utilization number from top?

How would I get the number for CPU Utilization from running the top command on a specific user?

Advertisement

Answer

Pipe top to awk and add up the CPU utilization column:

top -b -n 1 -u username | awk 'NR>7 { sum += $9; } END { print sum; }'

That awk command says “For rows (from top) greater than row 7, add up the number in field 9 $9 and store it in variable sum. Once you have gone through all of the rows in the piped top command, print out the value in variable sum“.


If the -u flag isn’t working on your system, you can just stick the username search with the NR>7 condition:

 top -b -n 1 | awk 'NR>7 && $2=="root" { sum += $9 } END { print sum }'

If you wanted to print the percent used for each user listed in top, you could chuck that second condition and switch sum to be an array:

 top -b -n 1 | awk 'NR>7 {users[$2]+=($9)} END {for(user in users){print user,users[user]}}'

One last thing. I believe that the percent cpu may need to be divided by the number of cores in your system. Like… I believe it might be possible to see a number greater than 100 pop up here.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement