Memory and cpu usage in 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

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.

Читайте также:  Kali linux repository yandex

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

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.

Источник

Читайте также:  Linux what uses ram

How To Monitor Your CPU and RAM in Linux

Monitor Your CPU and RAM in Linux

Whether we’re using a Raspberry Pi or a data center server, we need to know how our CPU and RAM are performing and, in Linux, there are a plethora of commands and applications that we can use. At the basic low level “How much RAM have I used?” to inspecting the CPU for vulnerabilities such as Spectre, there are commands at our disposal.

We are going to look at a number of different ways to get RAM and CPU data in the terminal, before we finally look at two applications which can provide a basic level of assurance, at a glance.

These commands will work on most Linux machines. Our test PC ran Kubuntu 21.10 but we are also certain that you can also run through this how-to on a Raspberry Pi. All of the how-to is performed via the Terminal.

How to Check Your CPU in Linux

1. Open a terminal.

2. Use the cat command to display the data held in /proc/cpuinfo.

This command will produce a lot of text, typically it will repeat the same information for the number of cores present in your CPU.

A more concise means to get most of this information is via lscpu, a command that lists the CPU details.

1. Open a terminal.

2. Use lscpu to display the CPU details. The command is quite verbose and we can easily see the number of CPU cores, minimum and maximum CPU speed and the CPU architecture.

Using a little grep magic we can pull out just the information that we need.

1. Open a terminal.

2. Using a vertical pipe, send the output of the lscpu command to grep and search for “max”. This will give us the maximum possible CPU speed. Pipes are a way to send the output of one command as the input for another. Classic examples are piping the output of a command to a text file for later review.

Another means to get CPU information is using dmidecode, a command that dumps the DMI (SMBIOS) contents into something we can understand.

1. Open a terminal.

2. Type in the dmidecode command using sudo, and the argument -t 4. There are many DMI types, with a numerical reference used to pull information for that component. In this case -t 4 is for the CPU. We can replace the 4 with processor for the same effect.

How to Check Your RAM in Linux

1. Open a terminal window.

2. Use the free command. This will show the available memory, and how the memory has been allocated, in Kilobytes.

3. Use the -m switch to show the available memory in Megabytes, or -g for Gigabytes.

Alternatively use the -h switch to show the memory information scaled to the three shortest digits. Giving us at a glance information.

There is a similar way to /proc/cpuinfo for memory information.

1. Open a terminal window.

2. Use the cat command to print the contents of /proc/meminfo. The output is incredibly verbose and can prove useful for debug. In general use we would stick with free -m.

If we need to know the timings and breakdown of memory modules in a machine then we can use lshw.

1. Open a terminal window.

Читайте также:  Проверьте ваши права доступа astra linux

2. Using sudo, issue the lshw command with the -short switch (the device tree) and -C with the class memory.

We can also use dmidecode for a more detailed query.

Information at a Glance

Should we need a more general level of information, our current CPU speed, RAM usage, network bandwidth then we have two commands which can be installed.

How to Install and Use Htop

The standard top command is great, but htop is a much better alternative. Htop provides us with an interactive list of running processes.

1. Open a terminal window.

2. Update your list of repositories.

3. Install htop using apt.

4. Run htop.

At the top of the window we can see the utilization of our CPU cores, under that is our RAM, and finally is the swap.

We can scroll through the list with our cursor keys or search using F3 followed by the name of a process or application. Here we have searched for the GNU Image Manipulation Program (GIMP). We can kill the app by pressing F9.

To close htop, press F10.

How to Install and Use Bpytop

Our personal preference is bpytop, a Python implementation of htop but with much more to offer.

1. Open a terminal window.

2. Install bpytop using the Python package manager pip.

3. Run bpytop from the terminal.

Bpytop’s interface is split into a series of areas.

1. CPU Status
a. CPU Speed
b. Core utilization
c. Overall utilization

2. RAM Usage
a. Total RAM
b. Used RAM
c. Available RAM
d. Cache

3. Disk / Storage Usage
a. Used and free space on all mounted devices

4. Network Interface Usage
a. Up and down speeds

5. Processes (just like htop)
a. Process management

We can show or hide an area by pressing the corresponding number (1..4). If we just wanted CPU, RAM, storage and Network information then we press 4. To bring it back, press 4 again.

To filter the processes for a particular application.

1. Press f to filter. It has to be lower case f.

2. Type in the application / process name / Pid. The search will adapt to show the process, in our case GIMP.

3. Press T to terminate the process, or K to kill. These have to be upper case T and K.

To exit bpytop press q at any time.

Stay on the Cutting Edge

Join the experts who read Tom’s Hardware for the inside track on enthusiast PC tech news — and have for over 25 years. We’ll send breaking news and in-depth reviews of CPUs, GPUs, AI, maker hardware and more straight to your inbox.

By submitting your information you agree to the Terms & Conditions and Privacy Policy and are aged 16 or over.

Les Pounder is an associate editor at Tom’s Hardware. He is a creative technologist and for seven years has created projects to educate and inspire minds both young and old. He has worked with the Raspberry Pi Foundation to write and deliver their teacher training program «Picademy».

Источник

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