Get total cpu linux

How to get overall CPU usage (e.g. 57%) on Linux [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.

I am wondering how you can get the system CPU usage and present it in percent using bash, for example. Sample output:

Reopening I don’t understand why this was ruled as off-topic, could the ones who closed it please care to elaborate?

My understanding of /proc/stat is very limited, but this one-liner works good enough for me: cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v '‘ . With %.2f you can control the number of decimals you want to output, and with sleep 1 you can set the time you want to average over, that is, if it does what I think it does. You can put it in a bash while loop, to test it in realtime.

6 Answers 6

Take a look at cat /proc/stat

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it’s an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can «apt-get install» anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk ' else print ($2+$4-u1) * 100 / (t-t1) "%"; >' \ <(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat) 

But you have to install mpstat like you recommend above. Many people don't have that flexibility. cat /proc/stat then pipe is much easier than mpstat you recommend.

system + user + idle = 100%. So maybe something like: grep 'cpu ' /proc/stat | awk ' END '

I think that this solution doesn't show the current CPU load but the average cpu load since the CPU started.

@jlliagre, yes that's right. To calculate the CURRENT cpu usage not average, you will need to take $1 value then delay then take $1 value and see the difference. That's the current cpu usage.

top -bn1 | grep "Cpu(s)" | \ sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \ awk '' 

A more accurate result is given when I use top -bn2 , but it takes a long time. From what I've read, this seems to be the only way to get an accurate result.

The command in this answer appears to be written for systems where top -v returns procps-ng (e.g., Fedora). There's also procps , found on, e.g., Ubuntu and CentOS, where the command doesn't work (always indicates 100%, because parsing fails due to the line with the CPU figures being formatted differently). Here's a version that works with both implementations: top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -1 | awk -F'id,' -v prefix="$prefix" '< split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%s%.1f%%\n", prefix, 100 - v >'

Читайте также:  Astra linux vpn подключение

Side note: on OSX, use the following: top -l 2 -n 0 -F | egrep -o ' \d*\.\d+% idle' | tail -1 | awk -F% -v prefix="$prefix" '< printf "%s%.1f%%\n", prefix, 100 - $1 >' .

Try mpstat from the sysstat package

> sudo apt-get install sysstat Linux 3.0.0-13-generic (ws025) 02/10/2012 _x86_64_ (2 CPU) 03:33:26 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle 03:33:26 PM all 2.39 0.04 0.19 0.34 0.00 0.01 0.00 0.00 97.03 

Then some cut or grep to parse the info you need:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " ''a 

I'd change the awk part to: awk -F " " '' , which gives the output formatted like he wanted, but otherwise this looks good to me.

@jordanm All truths; I was more voting it up because it works. I'd do this, personally: mpstat | awk '$12 ~ /[0-9.]+/ < print 100 - $12 >'

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:

This will use awk to print out 100 minus the 12th field (idle), with a percentage sign after it. awk will only do this for a line where the 12th field has numbers and dots only ( $12 ~ /8+/ ).

You can also average five samples, one second apart:

$ mpstat 1 5 | tee /dev/tty | awk 'END' 

Its better to run "mpstat 2 1 |. " so that it shows stats for the last 1 second. Otherwise, by default, mpstat shows stats since beginning and that does not change much as time progresses

@Sarang Thank you so much!! Finally I can get the results that conky is displaying as well. Unfortunately, this line is VERY slow, almost taking up to one whole second to execute.

@syntaxerror It takes exactly 2 seconds because if you look at the command help you see that the first argument is that it's the interval but it only executes once because of the second argument so it waits 2 full seconds until it returns the result.

Question is closed, so added my (similar) answer to yours 🙂 Hope you don't mind. Like you, I was inspired by Peter Liljenberg's answer.

EDITED: I noticed that in another user's reply %idle was field 12 instead of field 11. The awk has been updated to account for the %idle field being variable.

This should get you the desired output:

mpstat | awk '$3 ~ /CPU/ < for(i=1;i<=NF;i++) < if ($i ~ /%idle/) field=i >> $3 ~ /all/ < print 100 - $field >' 

If you want a simple integer rounding, you can use printf:

mpstat | awk '$3 ~ /CPU/ < for(i=1;i<=NF;i++) < if ($i ~ /%idle/) field=i >> $3 ~ /all/ < printf("%d%%",100 - $field) >' 

mpstat 1 1 | awk '$3 ~ /CPU/ < for(i=1;i<=NF;i++) < if ($i ~ /%idle/) field=i >> $3 ~ /all/ < printf("%d",100 - $field) >' works great for me, thanks. note the mpstat 1 1 to ensure that the cpu usage is sampled over a second

Do this to see the overall CPU usage. This calls python3 and uses the cross-platform psutil module.

printf "%b" "import psutil\nprint('<>%'.format(psutil.cpu_percent(interval=2)))" | python3 

The interval=2 part says to measure the total CPU load over a blocking period of 2 seconds.

Читайте также:  Linux local host file

The python program it contains is this:

import psutil print('<>%'.format(psutil.cpu_percent(interval=2))) 

Placing time in front of the call proves it takes the specified interval time of about 2 seconds in this case. Here is the call and output:

$ time printf "%b" "import psutil\nprint('<>%'.format(psutil.cpu_percent(interval=2)))" | python3 9.5% real 0m2.127s user 0m0.119s sys 0m0.008s 

To view the output for individual cores as well, let's use this python program below. First, I obtain a python list (array) of "per CPU" information, then I average everything in that list to get a "total % CPU" type value. Then I print the total and the individual core percents.

import psutil cpu_percent_cores = psutil.cpu_percent(interval=2, percpu=True) avg = sum(cpu_percent_cores)/len(cpu_percent_cores) cpu_percent_total_str = ('%.2f' % avg) + '%' cpu_percent_cores_str = [('%.2f' % x) + '%' for x in cpu_percent_cores] print('Total: <>'.format(cpu_percent_total_str)) print('Individual CPUs: <>'.format(' '.join(cpu_percent_cores_str))) 

This can be wrapped up into an incredibly ugly 1-line bash script like this if you like. I had to be sure to use only single quotes ( '' ), NOT double quotes ( "" ) in the Python program in order to make this wrapping into a bash 1-liner work:

printf "%b" \ "\ import psutil\n\ cpu_percent_cores = psutil.cpu_percent(interval=2, percpu=True)\n\ avg = sum(cpu_percent_cores)/len(cpu_percent_cores)\n\ cpu_percent_total_str = ('%.2f' % avg) + '%'\n\ cpu_percent_cores_str = [('%.2f' % x) + '%' for x in cpu_percent_cores]\n\ print('Total: <>'.format(cpu_percent_total_str))\n\ print('Individual CPUs: <>'.format(' '.join(cpu_percent_cores_str)))\n\ " | python3 

Sample output: notice that I have 8 cores, so there are 8 numbers after "Individual CPUs:":

Total: 10.15% Individual CPUs: 11.00% 8.50% 11.90% 8.50% 9.90% 7.60% 11.50% 12.30% 

For more information on how the psutil.cpu_percent(interval=2) python call works, see the official psutil.cpu_percent(interval=None, percpu=False) documentation here:

psutil.cpu_percent(interval=None, percpu=False)

Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.

Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

I use the above code in my cpu_logger.py script in my eRCaGuy_dotfiles repo.

References:

Источник

How can I get Linux to show total CPU usage?

I want to show how much the CPU is used over time. Using system monitor, I am able to show CPU usage, but only the 4 individual cores. I want to be able to show a graph of the total CPU usage. In other words, CPU core 1+2+3+4 = total, total

This really depends on what window manager you're using, unless you're looking for a specific application. Off-hand, I know GNOME and XFCE both include a CPU graph, so it's likely your system already has one built into the WM - see if you can add any "widgets" or taskbar entries.

Читайте также:  Права файлов linux коды

I think the 'top' command shows the total usage (as opposed to pressing '1' which shows the individual cores)

2 Answers 2

You can use conky to do this.

Conky is an application that draws an overlay on your desktop showing different system information. You can customise what is shown by creating a ".conkyrc" file in your home directory.

This is the .conkyrc file I use (It's a modified version of the one in PartedMagic):

# the list of variables has been removed from this file in favour # of keeping the documentation more maintainable. # Check http://conky.sf.net for an up-to-date-list. # set to yes if you want Conky to be forked in the background background yes # X font when Xft is disabled, you can pick one with program xfontsel #font 5x7 #font 6x10 font 7x13 #font 8x13 #font 9x15 #font *mintsmild.se* #font -*-*-*-*-*-*-34-*-*-*-*-*-*-* # Use Xft? use_xft no # Xft font when Xft is enabled xftfont Bitstream Vera Sans Mono:size=11 # Text alpha when using Xft xftalpha 0.8 # Print everything to stdout? # out_to_console no # Print everything to console? # out_to_console no # Update interval in seconds update_interval 5.0 # This is the number of times Conky will update before quitting. # Set to zero to run forever. total_run_times 0 #own_window_title Parted Magic - conky # Create own window instead of using desktop (required in nautilus) own_window yes # If own_window is yes, you may use type normal, desktop or override own_window_type normal # Use pseudo transparency with own_window? own_window_transparent yes # If own_window_transparent is set to no, you can set the background colour here own_window_colour black # If own_window is yes, these window manager hints may be used own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager #own_window_hints below,skip_taskbar,skip_pager # Use double buffering (reduces flicker, may not work for everyone) double_buffer yes # Minimum size of text area minimum_size 280 5 # Draw shades? draw_shades yes # Draw outlines? draw_outline no # Draw borders around text draw_borders no # Draw borders around graphs draw_graph_borders yes # Stippled borders? stippled_borders 4 # border margins border_margin 4 # border width border_width 1 # Default colors and also border colors default_color white default_shade_color black default_outline_color black # Text alignment, other possible values are commented #alignment top_left alignment top_right #alignment bottom_left #alignment bottom_right #alignment none # Gap between borders of screen and text # same thing as passing -x at command line gap_x 15 gap_y 15 # Subtract file system buffers from used memory? no_buffers yes # set to yes if you want all text to be in uppercase uppercase no # number of cpu samples to average # set to 1 to disable averaging cpu_avg_samples 2 # number of net samples to average # set to 1 to disable averaging net_avg_samples 2 # Force UTF8? note that UTF8 support required XFT override_utf8_locale no # Add spaces to keep things from moving about? This only affects certain objects. use_spacer none TEXT $Hostname: $nodename $Linux Kernel: $kernel $CPU Details: $machine, $freq(MHz) $CPU History: $$ $CPU Usage:$ $cpu% $ $RAM Usage:$ $mem ($memperc%) $ $Available RAM:$ $memmax $color$stippled_hr $alignc$Processes:$color $processes $Running:$color $running_processes $alignc$(top 5 sorted by CPU usage) $ NAME PID CPU% MEM% $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $alignc$(top 5 sorted by MEM usage) $ NAME PID CPU% MEM% $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $color$stippled_hr $alignc$System Uptime:$ $uptime $ Battery: $battery_short ($battery_time) $ $

Источник

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