Get process cpu usage linux

Retrieve CPU usage and memory usage of a single process on Linux?

I want to get the CPU and memory usage of a single process on Linux — I know the PID. Hopefully, I can get it every second and write it to a CSV using the ‘watch’ command. What command can I use to get this info from the Linux command-line?

22 Answers 22

(You can leave off «cmd» but that might be helpful in debugging).

Note that this gives average CPU usage of the process over the time it has been running.

The assumption would be that if you care about a single processes’ memory usage enough to monitor it like this, it’s using a significant amount of memory so that the extra couple-of-megabytes due to shared mappings isn’t an issue.

Keep in mind that %cpu «is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage» (see manpage of ps ). This is not the real just in time CPU usage. It can also be very different from what top shows, for instance.

as said from Xebeche just above, ps -e -o pcpu,args will show the cpu average over the lifetime of the process, which is obviously not what you want if it is a long running process

This auto-refreshes the CPU usage so it’s good for monitoring.

@MatthiasBraun should be top -p $(pgrep -d’,’ process_name) please see stackoverflow.com/a/8710740/2402577

ps command (should not use):

Use top to get CPU usage in real time(current short interval):

top -b -n 2 -d 0.2 -p 6962 | tail -1 | awk »

  • -b : Batch-mode
  • -n 2 : Number-of-iterations, use 2 because: When you first run it, it has no previous sample to compare to, so these initial values are the percentages since boot.
  • -d 0.2 : Delay-time(in second, here is 200ms)
  • -p 6962 : Monitor-PIDs
  • tail -1 : the last row
  • awk » : the 9-th column(the cpu usage number)

This is the most accurate answer to get the current CPU usage, not an average over the lifetime of the process.

You can get the results by the name of the process using

the -C option allows you to use process name without knowing it’s pid.

e.g. to monitor these two process IDs (12345 and 11223) every 5 seconds use

$ pidstat -h -r -u -v -p 12345,11223 5 

pidstat also gives a nice average. just a shame i have not found a more elegant way of pidstat -u 1 10 | grep ^Average | sort -r -n -b -k 8,8

Launch a program and monitor it

Читайте также:  Smart board driver linux

This form is useful if you want to benchmark an executable easily:

topp() ( if [ -n "$O" ]; then $* & else $* &>/dev/null & fi pid="$!" trap "kill $pid" SIGINT o='%cpu,%mem,vsz,rss' printf '%s\n' "$o" i=0 while s="$(ps --no-headers -o "$o" -p "$pid")"; do printf "$i $s\n" i=$(($i + 1)) sleep "$" done ) 
%cpu,%mem,vsz 0 0.0 0.0 177584 1 0.0 0.1 588024 2 0.0 0.1 607084 3 0.0 0.2 637248 4 0.0 0.2 641692 5 68.0 0.2 637904 6 80.0 0.2 642832 

where vsz is the total memory usage in KiB, e.g. the above had about 600MiB usage.

If your program finishes, the loop stops and we exit topp .

Alternatively, if you git Ctrl + C, the program also stops due to the trap : How do I kill background processes / jobs when my shell script exits?

  • T=0.5 topp ./myprog : change poll interval
  • O=1 topp ./myprog : don’t hide program stdout/stderr. This can be useful to help correlate at which point memory usage bursts with stdout.

ps vs top on instantaneous CPU% usage

Note that the CPU usage given by ps above is not «instantaneous» (i.e. over the last N seconds), but rather the average over the processes’ entire lifetime as mentioned at: https://unix.stackexchange.com/questions/58539/top-and-ps-not-showing-the-same-cpu-result ps memory measures should be fine however.

That thread as well as: How can I determine the current CPU utilization from the shell? suggest that the Linux kernel does not store any more intermediate usage statistics, so the only way to do that would be to poll and calculate for the previous period, which is what top does.

We could therefore use top -n1 instead of ps if we wanted that:

toppp() ( $* &>/dev/null & pid="$!" trap exit SIGINT i=1 top -b n1 -d "$" -n1 -p "$pid" while true; do top -b n1 -d "$" -n1 -p "$pid" | tail -1; printf "$i "; i=$(($i + 1)); done ) 

as mentioned e.g. at: https://stackoverflow.com/a/62421136/895245 which produces output of type:

 top - 17:36:59 up 9:25, 12 users, load average: 0.32, 1.75, 2.21 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie %Cpu(s): 13.4 us, 2.5 sy, 0.0 ni, 84.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st MiB Mem : 31893.7 total, 13904.3 free, 15139.8 used, 2849.7 buff/cache MiB Swap: 0.0 total, 0.0 free, 0.0 used. 16005.5 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 706287 ciro 20 0 590436 40352 20568 R 106.7 0.1 0:00.16 node 706287 ciro 20 0 607060 57172 21340 R 126.7 0.2 0:00.35 node 1 706287 ciro 20 0 642008 80276 21812 R 113.3 0.2 0:00.52 node 2 706287 ciro 20 0 641676 93108 21812 R 113.3 0.3 0:00.70 node 3 706287 ciro 20 0 647892 99956 21812 R 106.7 0.3 0:00.87 node 4 706287 ciro 20 0 655980 109564 21812 R 140.0 0.3 0:01.09 node 

My only problems with this is that top is not as nice for interactive usage:

  • Ctrl + C does not exit the above command, not sure why trap exit is not working as it does with ps . I have to kill the command Ctrl + \ , and then that does not kill the process itself which continues to run on the background, which means that if it is an infinite loop like a server, I have to ps aux and then kill it.
  • the not exit automatically when the benchmarked program exits
Читайте также:  Xor in с linux

Maybe someone more shell savvy than me can find a solution for those.

ps memory measurements should be the same as top however if you’re just after memory.

Источник

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.

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)
Читайте также:  Настройка iscsi initiator linux

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.

Источник

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