Download as pdf
Download as pdf
You are on page 1of 15
14 Command Line Tools to Check CPU Usage in Linux CPU performance is one aspect of measuring the performance of a system. Monitoring the performance of CPU Is, essential to debug processes inside any system, manage system resources, making system decisions, and evaluating and examining systems in realtime, There are a lot of tools available to monitor and display CPU performance. Operating systems have builtin system calls, which these tools rely on to extract the performance readings. In this tutorial, we will explore the best CPU usage monitoring tool and their usages in any Linux based distros. 1) Top ‘The top command displays real-time view of performance-related data of all running processes in a system. By default, the top command updates data every 5 seconds. Type ‘top’ from the terminal to view the statistical data related to the performance of a system, ‘To modify the output of top command, press: 'P'to sort by CPU usage. ‘I to remove the idle processes from the display and to revert back press '' again, "M to sort the data by memory usage. 'S! to sort by how long the processes have been running type. 'P'to sort by CPU usage. "U! to view processes owned by a specific user. "K'to kill processes. 'R'to renice processes, 2) lostat The jostat command list CPU utilization, device utilization and network file system utilization. This utility display system's average CPU utilization since the last reboot. Running the following command without any options displays all the three reports, To list the individual report use -c, -d and -h switch for CPU utilization, device utilization and network file system utilization. The following command will break the CPU utilization into user processes, system processes, I/O wait and idle time. The following command will display extended statistics (-x), the number of times (-t) each report should be displayed for CPU utilization (-c). 3) Vmstat The vmstat command will display statistics about system processes, memory, swap, /O, and the CPU performance. For displaying statistics, the data is collected from the last time the command was run to the present. In case the command never being run, the data will be from the last reboot to the current time. ‘On multiple CPU systems, vmstat averages the number of CPUs into the output. The vmstat command updates its output like top command. The following command will update its report every 5 seconds until there is an interrupt. The following command will display the data that will update in every 5 seconds and the values will be re-measured and reported every 1 second. The first line prints the average values since the last time the computer was rebooted. The rest of the lines will display their respective current values, A normal user can run vmstat command, 4) Mpstat Mpstat is part of the sysstat package in Linux, The mpstat command writes to standard output about activities for each available processor, processor 0 being the first one, If no activity has been selected, then the default report is the CPU utilization report. mpstat without any option will display Global Average Activities of all CPUs ‘mpstat with -p option and ‘ALL’ will list statistics about all CPUs one by one starting from 0. The following command will ist average CPU usage for 4 times, each after 2 seconds. 5) Sar ‘The sar is a performance monitoring tool for collecting, viewing and recording performance data and can list what a system is doing all the time. Sar commandcan generate report and email them to system admin. The statistics reported by sar include 1/0 transfer rates, paging activity, process-related activities, interrupts, network activity, memory and swap space utilization, CPU utilization, kernel activities and TTY statistics, among others. Run sar without any option and check the output. The default output list statistics for every 10 minutes and a final average. Display CPU statistics 3 times with 2 second interval corey The following command displays cumulative real-time CPU usage of all CPU for every 2 seconds a total of 3 times. The “P ALL’ option displays statistics for ALL the individual Cores. If your system has 4 cores then the ‘CPU column’ will contain the number 0, 1, 2, 3 indicating the corresponding CPU core numbers. The '2 3" option displays the statistics every 2 seconds for 3 times, The “-P 2 option displays statistics for third core every 2 seconds for 3 times. 6) CoreFreq CoreFreq is a CPU performance monitoring software designed for 64-bits Processors w/ architectures Intel Atom, Core2, Nehalem, SandyBridge and superior, AMD Family. The CoreFreq provides a framework for retrieving CPU data with a high degree of precision. The kernel module, daemon, and userland command-line interface (CLI) are the three parts of Corefreq, The kernel module will have full access to the host. Itis its responsibility to gather the low-level data. The userland daemon collects the data, You should be root user to run the daemon, Finally, CoreFreq comes with a terminal interface to report data in a nice human-readable format. That CL! tool is an ordinary process and may be used by the end user, Prerequisite i) CoreFreq uses the low-level counter and hence you should first disable NMI watchdog through /ete/defaultigrub. Edit etc/defaultigrub and add the ‘nmi_watchdog=0' kernel command line argument and subsequently run update-grub. # vt fete/aerountyerub ii) No Virtualization, VMs don't provide access to the registers that the CoreFreq driver employs. Install CoreFreq # sudo apt-ge # ed ConeFreg install pit dns buile-essential 1ibe6-dev Lsbpthread-stubs®-dev ctps:/i/eithub.con/eyring/CoreF reg. ait Install the kernel module with insmod List the CoreFreq module with Ismod 1 stad | grep conefreg corefreak 19152 @ The output of dmesg command shows CoreFreg has been recognized by the processor. # sudo dnesg | grep Corefreg [ 411.825745] Corerrea: Processor (06_3F] Architecture (Haswell/Mobi.e] CPU [1/2] Start the CoreFreq daemon sudo «/corefregd -1 & Now start the corefreq client as a user. F -seorefreg-cli 7) Htop Htop is a process viewer and a text-mode application for system monitoring in real-time like top. It displays a complete list of the processes that are running and Is easy to use. It Is based on ncurses for viewing the processes ina GUM-Ike environment running in the terminal. Htop displays usage per CPU along with memory and swap usage with a significant text graph printed at the top, Htop is very much convenient to use and easy to understand, Once you start using HTOP, you might not return to TOP, Install htop using the following command in the terminal # sudo apt-get install htop Run htop using the following command. 8) Nmon nmon (Nigel's performance Monitor for Linux & AIX) has been developed by IBM employee Nigel Griffiths. This tool is used to monitor system resources such as CPU, memory, network, disks, file systems, NFS, top processes in the terminal. NMON supports various architectures like POWER, x86, x86_64, Mainframe and ARM (Raspberry Pi). This tool helps system administrator to tune, benchmark performance information to troubleshoot the CPU/system performance when there is some issues. For real-time monitoring, it uses curses library for low CPU impact and displays statistics on the screen and update in every two seconds. nmon consumes less CPU memory as compared with other tools since it Uses curses library. Installation nstall nnon (ubuntu) 08) sudo apt: # sudo yor Snstall anon (Ce CentOS users need to instal/enable EPEL Repository in order to install nmon. ‘Type nmon in the terminal and press enter, nmon will display a welcome screen with all the options to use it further. If you want to display CPU utilization, press c and to hide the CPU utlization widgets statistics, press ‘c' again 9) Glances lances is a cross-patform curses-based monitoring tool writen in Python that uses the psutl brary to fetch data from the system. Glance monitor CPU, Load Average, Memory, Network Interfaces, Disk I/O, Processes and File System spaces utllization. Install glances in your system with the following command. In Ubuntu: ‘sudo apt-get Anstall glances In Centos: 4 sudo yun Anstall glances You can run Glances in 3 modes- 1, Standalone If you want to monitor your local machine(Standalone), simply run- f glances 2, Client/Server If you want to remotely monitor a machine then execute the following on the server. and then from the client, execute the following command. # glances -© server where @server is the IP address or hostname of the server. 3, Webserver Run the glances in web server mode by executing the following command in the terminal, f glances -w lances web server started on http://0.0,0.0:63208/ To change the refresh rate of the page, just add the period in seconds at the end of the URL. For example, to refresh the page every 30 seconds, append 10 to the glances server URL from the browser. hetor//@servers61208/30 10) Cpustat Cpustat is like a fancy sort of top that does different things. Most performance tools average CPU usage over a few seconds or even a minute. This results in a fantasy of excess capacity because of an abrupt increase in resource usage that is blended in with less busy periods. On the other hand, cpustat takes higher frequency samples of each process and summarizes these samples at a lower frequency. For example, it can measure a process in every 200ms and summarize the samples in every 5 seconds, including min/average/max values for some metrics. Install Cpustat Cpustat is written in Go language. Therefore, you need GO in your system. Ifit is not there then install it using following ‘commands in the terminal. In Ubuntu 1 sudo add-apt-repository ppasiongsleep/golang-backports # sudo aptaget update f Sudo apt-get install gola In Centos f yun install golang ‘Once Golang is installed in your system then create a directory for Cpustat and make this directory available to the GOPATH. F wksin cpustat F export GOPATHA$HONE/epustat Install Cpustat and verify that the directories are copied over to the folder cpustat 4 go get pithub.con/uber-conon/cpustat 4 4 custat au Is, ‘Add bin folder to the PATH environment variable. You can also add the following line to ~/.bashre or /elc/profile depending on what you are using. 1 export PATHASPATH:/root/cpustat/oin There are two ways of displaying this data. Either a pure text list of the summary interval or a colorful scrolling dashboard of each sample. To display data in fancy terminal mode, execute the following command in the terminal. To run in pure text mode, use the following command. In text mode, few system-wide summary metrics come from Iprocistat, The following command will take a sample of all processes in every 500ms and summarize this data after 10 samples, which is every 5 seconds. Use the following command to measure processes that are owned by either user root or user ubuntu. The overall system stats will still be measured, Only measure processes of "apache" or "mysql". The -p option of cpustat takes a list of process ids returned by pgrep. grep is used to get the process ids ( -d option ). F epustat -p pera , apachez\ Inysqid) Use the following command to write memory profile in a file # cpustat -nenprofile test.txt 11) perf Perf can measure CPU performance counters, tracepoints, kprobes, and uprobes that is included in the Linux kernel, under tools/perf. perf began as a too! for using the performance counters subsystem in Linux, and has had various enhancements to add tracing capabilities. The perf tools are integrated into the Linux kernel since the 2.6 version and are based on the perf events subsystem. The perf profiler uses hardware counters to profile the application. The result of this profiler is explicit and fast, The perf utility can be found in the linux-tools package, Measure entire system for 26 seconds vsing per‘. f pert stat If you are interested in finding CPU performance for a particular ‘command’ like cp. The following perf command will profile cp while itis copying the entire directory Documents to new location (Docs). If you want to find CPU counter statistics for a specified PID then use the following command until CTRL#C is pressed, Find the basic CPU statistics, system wide, for 10 seconds using the following perf command. You can also omit any one of the options under -e option to be more specific. # perf stat -e cycles, instructions cache-references, cache sses,bus-cyeles -3 sleep 1¢ Collect Sample on-CPU user instructions, for 5 seconds and then use perf report to view the report. perf record =e cyclestu -2 -- sleep 5 Collect sample CPU stack traces, once every 10,000 Level 1 data cache misses, for 5 seconds and then use perf report to view the report 4 perf necord =e L1-deache-load-nisses -c 10000 -2g -- sleep 5 # pert report 12) tiptop Tiptop reads hardware performance counters and displays statistics about running Linux processes, such as IPC, or cache misses. It provides a dynamic real-time view of the tasks running in the system. Tiptop is very similar to top, but the information displayed comes from hardware counters. Ithas two running modes, live-mode and batch-mode. In both modes, the system is periodically queried for the values of hardware counters, and various ratios are printed for each task. F tiptop -b ‘tiptop = up 1 days, 15:36, load average: 0.68, 8.€1, 0.85 Fr vay 19 08:36:25 utc 2617 delay: 2.00 Adle: @ threads: @ sereen @: default PID [ CPU] SVS P Meyele Mi IPC HSS HBMES HaUS COMMAND 45 5,91 1,9 rpebine 13) ps command We can use ps command to find cpu usage for each process or users. Given few examples to understand To display the highest CPU & Memory utilization by processes run by root, psu | sort -kea =r | head -5 USER PID XCPU MEM SZ RSS TTY STAT START TIME COMMAND root 473 0,8 8.3 110036 836 ttyi Sst Apr2i 8:08 /sbin/agetty ~-noclear ttyt Linux root 10298 8.0 8.1 107904 664 pts/@ S> 17:31 0:00 head -5, root 10289 8.0 0.1 116444 990 pts/e Sp 17:31 0:80 sort -k 1 ~ root 10288 8.0 0,3 151086 1824 pts/@ Re 17:32 6:08 ps u Run the following command to display CPU usage for the specific command: hood -8 9.8 sshd: root [piv] 0.8 sshd: root [priv] 0.6 sshd: root [priv] 9.0 [writeback) 9.8 [natehdog/9} 9.0 [vietsesi-scan} 9.0 [vbatoon} ‘To show processes for all users and not attached to a terminal in full format listing with a sort 1 ps -auxf | sort -nr -K 3 | head -10 root 19513 @.5 2.8 189476 5360 7 5s 17:48 @:00 \_ sshd: v Foot 10511 @.5 £18 144476 5388 ? Se 17:48 @100 \_ eahds USER P10 ACPU AHEM VSZ RSS TTY STAT START TIME COMMND sshd 10514 9.0 0.4 88228 2496 ? 5 17:48 8:08 \_ sna: root [net] sshd 19512 9.8 9.4 88228 2592 7 5 17:48 e:@2 |"\_ sshd: root [net rpeuser 2492 0.0 8.3 42348 1720 ? $5 Apr2i @:08 /usr/sbin/rpe. state pe 2334 0.9 @.2 64948 1416 ? $= Apr2i 8:21 /sbin/rocbind -¥ root 9346 8.6 8,0 8 @ 2 § 26:02 8:00 \_ [kuorker/@:0) root 92 8.0.08 @ ? 5 Aprat 0:01 \_ [kavdita] root 9 8.0 8.8 0 8 ? R Apr2i e:05 \_[rcu_sched] priv] priv] no-notity 14) dstat command dstat command is a versatile tool for generating system resource statistics and it would also show cpu stats. You need to install it in order to use it On Centos 4b yu install -y dete On Ubuntu 4 apt-get instal! dstat To monitor program that is using the most CPU and consuming the most amount of memory. Conclusion In this tutorial, we have explored few CPU performance monitoring tool along with their usages. Be sure to read man pages for each of them, as it also documents the usages in detail. Remember that using these tools also takes a CPU slice, For example, top takes 3%-4% of CPU while glances take 15% to 20% of CPU. So while using any one of these, you need to consider this aspect as well. In a nutshell, you will be able to find which process is taking more CPU time, is there enough free memory, whether processes are stalled while waiting for VO viz. disk or network access to complete readiwrite and much more by using a combination of few of them. Read Also: + How to Monitor Linux Performance Using Sar Command * Install htop 2.0.2 and Use Command Line on Linux

You might also like