How to Display the Total CPU Size Used by an Application on Linux?

The previous article explained how to display the total size of memory used by applications on Linux. This article will explain how to display the total CPU size used by an application on Linux.

 

Problem

How to display the total CPU size used by an application on Linux?

 

Solution

You can use the application commonly used to see processes that run on Linux, such as top and htop, because it will display the CPU usage. Still, I want to display the size of the CPU used by an application because the display of the two commands is still confusing. Here are some scripts that can be used to see the size of the CPU used by an application on Linux:

A. Displays CPU per one application

Run the command below to see the CPU size used by an application (this script will display the size of the CPU used by the Vivaldi browser):

echo "Firefox browser use $(ps -C firefox -o %cpu --no-headers 2>/dev/null \
| awk -v cores=$(nproc) '{sum+=$1} END {if (NR>0) printf "%.1f%% CPU (of %d cores)", \
sum, cores; else print "0% CPU (not running)"}')"

 

Then the memory used by Firefox will be displayed as shown in the picture below:

Display the size of the total CPU used by Firefox

 

B. Display the CPU for more than one application

If you want to display the CPU size used by more than one application, use the command below (this script will display the CPU size used by the Vivaldi and Firefox browsers):

for app in firefox-bin vivaldi-bin; do   echo -n "$app: ";   ps -C "$app" -o %cpu --no-headers 2>/dev/null |     awk -v cores=$(nproc) '{
      sum+=$1
    } END {
      if (NR>0) printf "%.1f%% CPU (of %d cores)\n", sum, cores
      else print "0% CPU (not running)"
    }'; done

 

Then the CPU used by Vivaldi and Firefox browsers will be displayed as shown in the picture below:

Display the size of the total CPU used by Vivaldi and Firefox

 

C. Displays the 5 apps that use the most CPU

Run the script below to see the 5 Linux applications that use the most CPU:

{ 
  echo -e "Application Name       %CPU"
  ps -eo comm,%cpu --no-headers | awk '{cpu[$1]+=$2} END {for (p in cpu) printf "%-20s %6.2f\n", p, cpu[p]}' | sort -k2 -nr | head -n 5
}

 

The script above will show the 5 Linux applications that use the most CPU:

display the total CPU size used
Display the Linux applications that use the biggest CPU

 

Note

If you want to know the simple Linux command to display the memory and CPU of an application, you can use the command below (for this case, I chose the Firefox application):

ps -p $(pgrep -d ',' firefox-bin) -o pid,user,%cpu,%mem,cmd

 

Then there will be a display as below:

display the total CPU size used
Simple Linux command to display RAM and CPU

 

References

stackoverflow.com
lindevs.com
tecmint.com