Get cpu load on linux

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

Читайте также:  Linux dpkg install dependencies

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.

Источник

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.

Article on how to check CPU utilization in Linux from the terminal.

  • 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.

Читайте также:  Серверный кэш 1с линукс

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:

Читайте также:  What is sip server in linux

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.

Источник

C API for getting CPU load in linux

Accessing /proc is the unix way to do things. Everything’s a file. I gather you are a MS programmer? They always seem uncomfortable with this concept.

5 Answers 5

If you really want a c interface use getloadavg() , which also works in unixes without /proc .

It has a man page with all the details.

Indeed. All the puffing above about the «unix way» notwithstanding, this really is the portable way to do it. On linux, of course, it’s just a library function on top of a /proc read.

Load average is not a representation of the cpu load. By cpu load, I mean how much waiters are busy in your restaurant. Load average gives you the number of customers waiting outside to get seated + number of customers currently eating. This is not the same thing. I believe using /proc/stat is more relevant here.

The preferred method of getting information about CPU load on linux is to read from /proc/stat, /proc/loadavg and /proc/uptime. All the normal linux utilities like top use this method.

 /proc/loadavg The first three fields in this file are load average figures giving the number of jobs in the run queue (state R) or waiting for disk I/O (state D) averaged over 1, 5, and 15 minutes. They are the same as the load average numbers given by uptime(1) and other programs. The fourth field consists of two numbers sepaâ rated by a slash (/). The first of these is the number of curâ rently executing kernel scheduling entities (processes, threads); this will be less than or equal to the number of CPUs. The value after the slash is the number of kernel scheduling entities that currently exist on the system. The fifth field is the PID of the process that was most recently created on the system. 

Источник

Оцените статью
Adblock
detector