10

I know the top command to see the process of CPU and memory usage, but some users of the system can generate a lot of processes, if I wanna know total CPU and memory usage of an user,I must count it by my own,so,is there a command which can view total CPU and memory usage of per system user in Linux,and order by system username?

3
  • well by pressing u in the top command you can see the users and their processes.
    – Kunal
    May 27, 2015 at 4:30
  • From user Mohammad Rahimi: There is a system load indicator for toolbar which you can config to show overall CPU and usage. System Load Indicator, Multiload-ng
    – fixer1234
    Oct 4, 2018 at 19:59
  • Nowadays, looking at cgroups is probably the best way to get meaningful values.
    – Daniel B
    Oct 5, 2023 at 11:08

2 Answers 2

7

I don't think there's a direct way of doing it - but one way would be to parse the output of top. The following

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

does just that. For each process in top (for a given user) awk will strip the 9th delimited field (i.e. CPU %) 7 lines down (i.e. start of the top table) for each line, then sum them. Saves you fiddling about at least!

A couple of discussions around this...

Howtoforge, Stackexchange

1
  • The number of lines to skip depends on the number of cores installed. use 6 + n_cores to skip all. For my version of top (3.3.10), it is also the 7th field that contains the CPU usage.
    – reox
    Sep 27, 2023 at 8:46
2

Complementing @hygris command, we can add the following and have the information for all the users at the same time:

top -b -n 1  |\
 awk ' BEGIN{OFS="\t"} 
 NR>7{ sum[$2] += $9; t += $9;} 
END {print "user","%CPU" ; for (u in sum){print u,sum[u]}print "total",t}'

The above command will print the total at the end.

If you want to add the memory:

 top -b -n 1  |\
  awk ' BEGIN{OFS="\t"} 
     NR>7 { sum[$2] += $9; t += $9; mem[$2] += $10; tm += $10} 
     END {print "user","%CPU","%MEM" ; for (u in sum){
         print u"\t"sum[u]"\t"mem[u];} print "total",t,tm}' 

Then, of course, you can pipe and sort the output if that is your goal.

You must log in to answer this question.

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