- How can I determine the current CPU utilization from the shell? [closed]
- 7 Answers 7
- How to Check CPU Utilization in Linux with Command Line
- How To Check CPU Usage from Linux Command Line
- top Command to View Linux CPU Load
- mpstat Command to Display CPU Activity
- sar Command to Show CPU Utilization
- iostat Command for Average Usage
- Other Options to Monitor CPU Performance
- Nmon Monitoring Tool
- Graphical Utility Option
- How to get CPU usage
- 6 Answers 6
How can I determine the current CPU utilization from the shell? [closed]
How can I determine the current CPU utilization from the shell in Linux? For example, I get the load average like so:
Just FYI, the load average is not the CPU usage although it may indirectly show the CPU usage. It’s a number showing how many processes are out there running but waiting for resources, be it CPU or disk or something else.
can’t answer the question cause it’s closed but have a look at vmstat , as a bonus it works on BSDs as well.
7 Answers 7
Linux does not have any system variables that give the current CPU utilization. Instead, you have to read /proc/stat several times: each column in the cpu(n) lines gives the total CPU time, and you have to take subsequent readings of it to get percentages. See this document to find out what the various columns mean.
Because Space’s answer doesn’t work. It returns the average CPU usage since process start and not the current CPU usage. This answer is the correct one.
You can use top or ps commands to check the CPU usage.
using top : This will show you the cpu stats
using ps: This will show you the % cpu usage for each process.
ps -eo pcpu,pid,user,args | sort -r -k1 | less
Also, you can write a small script in bash or perl to read /proc/stat and calculate the CPU usage.
We tried, and «top -b -n 1» gives very inaccurate results. «top»‘s first iteration is very approximative, can give 10 percent instead of 60.
top’s calculation of %CPU is different from ps’s calc of %CPU. see this answer unix.stackexchange.com/questions/58539/…
The command uptime gives you load averages for the past 1, 5, and 15 minutes.
Unfortunately I need it to exit right away so I can parse the output. I’m hoping there is a file in /proc that I can read.
This will be something like this:
cpu 55366 271 17283 75381807 22953 13468 94542 0 cpu0 3374 0 2187 9462432 1393 2 665 0 cpu1 2074 12 1314 9459589 841 2 43 0 cpu2 1664 0 1109 9447191 666 1 571 0 cpu3 864 0 716 9429250 387 2 118 0 cpu4 27667 110 5553 9358851 13900 2598 21784 0 cpu5 16625 146 2861 9388654 4556 4026 24979 0 cpu6 1790 0 1836 9436782 480 3307 19623 0 cpu7 1306 0 1702 9399053 726 3529 26756 0 intr 4421041070 559 10 0 4 5 0 0 0 26 0 0 0 111 0 129692 0 0 0 0 0 95 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 369 91027 1580921706 1277926101 570026630 991666971 0 277768 0 0 0 0 0 0 0 0 0 0 0 0 0 ctxt 8097121 btime 1251365089 processes 63692 procs_running 2 procs_blocked 0
How to Check CPU Utilization in Linux with Command Line
Understanding CPU processor usage is important for overall system-performance measurement. From Linux enthusiasts to system admins, knowing how to monitor CPU utilization in Linux from the command line is crucial.
This guide will walk you through several options to check Linux CPU usage.
- A Linux-based computer (e.g., Ubuntu and CentOS)
- Access to a user account with sudo privileges
- A command prompt (Ctrl-Alt-T in Ubuntu, Menu > Applications > Utilities > Terminal in CentOS)
- (optional) A package installer, like apt or yum, usually included by default
Note: Use one of 5 available commands in Linux to check memory usage.
How To Check CPU Usage from Linux Command Line
top Command to View Linux CPU Load
Open a terminal window and enter the following:
The system should respond by displaying a list of all the processes that are currently running. It will also give a readout of users, tasks, CPU load, and memory usage.
This list can frequently change, as background tasks start and complete. One helpful switch is to launch top with the –i switch:
This hides all the idle processes, making it easier to sort through the list.
To quit the top function, press the letter q on your keyboard.
Some other useful commands while top is running include:
- M – sort task list by memory usage
- P – sort task list by processor usage
- N – sort task list by process ID
- T – sort task list by run time
To get assistance with top , you can press the letter h while it’s running. Or, you can enter the following at a command line:
This will display the manual page for the top command.
mpstat Command to Display CPU Activity
Mpstat is part of a software bundle called sysstat. Most RHEL-based distributions include this software package.
For Debian and Ubuntu systems, you’ll need to install the sysstat package.
In a terminal window, enter the following:
sudo apt-get install sysstat
Allow the process to complete.
If you’re running an older (4.x or older) version of CentOS or Red Hat derivative, you can use up2date to install sysstat:
sudo up2date install sysstat
For newer (5.x and later) installations of CentOS or Red Hat, sysstat can be installed using the following command:
Once the process finishes, you can use the mpstat command in the terminal as follows:
The system will display usage for each processor (or processor core).
The first line is a set of column labels. The second line is the value for each column:
- %usr – % CPU usage at the user level
- %nice – % CPU usage for user processes labeled “nice”
- %sys – % CPU usage at the system (Linux kernel) level
- %iowait – % CPU usage idling waiting on a disk read/write
- %irq – % CPU usage handling hardware interrupts
- %soft – % CPU usage handing software interrupts
- %steal – % CPU usage being forced to wait for a hypervisor handling other virtual processors
- %guest – % CPU usage spent running a virtual processor
- %idle – % CPU usage on idle time (no processes, and not waiting on a disk read/write)
You can add switches to the mpstat command.
The –P switch allows you to specify a single processor to report:
This would show you a report for the first processor (CPU 0).
This command would show you the total, like the basic mpstat command. It will also list processes by individual CPU.
The mpstat command only takes a snapshot of CPU usage.
To take a series of snapshots, use a number to indicate an interval and a second number to indicate the number of reports:
This example would generate 7 snapshots, each 5 seconds apart.
sar Command to Show CPU Utilization
The sar tool is a utility for managing system resources. It’s not limited strictly to CPU usage, but you can use the -u option to track CPU performance.
Use the following command to direct sar to monitor CPU usage at set intervals:
The –u option tells it to display CPU usage. The 5 indicates that it should display every 5 seconds. This will run indefinitely. To cancel, press Ctrl-C.
iostat Command for Average Usage
In a terminal, enter the following:
The system will display average CPU usage since the last boot. It will also display input/output load (disk read/write activity).
More information on iostat can be found on the Linux Manual pages.
Other Options to Monitor CPU Performance
Nmon Monitoring Tool
Nmon is a monitoring tool developed by Nigel Griffiths of IBM. To install Nmon on Ubuntu, enter the following:
To install to CentOS, enter the following:
The command to launch nmon is:
This will launch the utility, and display all the options. To view CPU usage, press the letter c. To switch back, press c again. For a list of commands, press h. To quit, press q.
Graphical Utility Option
Many server systems don’t waste processor cycles on a graphical user interface (GUI).
However, you may have a lightweight GUI, or you may be using a client Linux system. Some versions, like Ubuntu, have a built-in graphical monitoring tool.
To launch Ubuntu’s system monitor, enter the following in a terminal window:
This starts a task-manager-like application where you can monitor tasks and CPU usage.
Typically, GUI’s have a “task manager” or “system monitor” application. This can be used to monitor CPU usage in real-time.
There are many different methods to check CPU usage in Linux.
This guide outlines the primary methods using built-in Linux tools or third-party applications. These commands will help you track processor usage and performance of your system, giving you greater control.
How to get CPU usage
My Go program needs to know the current cpu usage percentage of all system and user processes. How can I obtain that?
I use Go (from golang.org) under Linux, but I would like to use something portable to other *nix if it’s possible.
Not exactly an answer, but I tried multiple ways to do it (including reading the proc/stat) file and then realised that the service is deployed on Kubernetes and we were already reporting the usage from the pod. So I went with that one instead.
6 Answers 6
Check out this package http://github.com/c9s/goprocinfo, goprocinfo package does the parsing stuff for you.
stat, err := linuxproc.ReadStat("/proc/stat") if err != nil < t.Fatal("stat read fail") >for _, s := range stat.CPUStats < // s.User // s.Nice // s.System // s.Idle // s.IOWait >
I had a similar issue and never found a lightweight implementation. Here is a slimmed down version of my solution that answers your specific question. I sample the /proc/stat file just like tylerl recommends. You’ll notice that I wait 3 seconds between samples to match top’s output, but I have also had good results with 1 or 2 seconds. I run similar code in a loop within a go routine, then I access the cpu usage when I need it from other go routines.
You can also parse the output of top -n1 | grep -i cpu to get the cpu usage, but it only samples for half a second on my linux box and it was way off during heavy load. Regular top seemed to match very closely when I synchronized it and the following program:
package main import ( "fmt" "io/ioutil" "strconv" "strings" "time" ) func getCPUSample() (idle, total uint64) < contents, err := ioutil.ReadFile("/proc/stat") if err != nil < return >lines := strings.Split(string(contents), "\n") for _, line := range(lines) < fields := strings.Fields(line) if fields[0] == "cpu" < numFields := len(fields) for i := 1; i < numFields; i++ < val, err := strconv.ParseUint(fields[i], 10, 64) if err != nil < fmt.Println("Error: ", i, fields[i], err) >total += val // tally up all the numbers to get total ticks if i == 4 < // idle is the 5th field in the cpu line idle = val >> return > > return > func main() < idle0, total0 := getCPUSample() time.Sleep(3 * time.Second) idle1, total1 := getCPUSample() idleTicks := float64(idle1 - idle0) totalTicks := float64(total1 - total0) cpuUsage := 100 * (totalTicks - idleTicks) / totalTicks fmt.Printf("CPU usage is %f%% [busy: %f, total: %f]\n", cpuUsage, totalTicks-idleTicks, totalTicks) >
It seems like I’m allowed to link to the full implementation that I wrote on bitbucket; if it’s not, feel free to delete this. It only works on linux so far, though: systemstat.go
The mechanism for getting CPU usage is OS-dependent, since the numbers mean slightly different things to different OS kernels.
On Linux, you can query the kernel to get the latest stats by reading the pseudo-files in the /proc/ filesystem. These are generated on-the-fly when you read them to reflect the current state of the machine.
Specifically, the /proc//stat file for each process contains the associated process accounting information. It’s documented in proc(5). You’re interested specifically in fields utime , stime , cutime and cstime (starting at the 14th field).
You can calculate the percentage easily enough: just read the numbers, wait some time interval, and read them again. Take the difference, divide by the amount of time you waited, and there’s your average. This is precisely what the top program does (as well as all other programs that perform the same service). Bear in mind that you can have over 100% cpu usage if you have more than 1 CPU.
If you just want a system-wide summary, that’s reported in /proc/stat — calculate your average using the same technique, but you only have to read one file.