Scheduled Maintenance: We are aware of an issue with Google, AOL, and Yahoo services as email providers which are blocking new registrations. We are trying to fix the issue and we have several internal and external support tickets in process to resolve the issue. Please see: viewtopic.php?t=158230

 

 

 

Terminal command to get CPU usage?

Off-Topic discussions about science, technology, and non Debian specific topics.
Post Reply
Message
Author
THX1138b
Posts: 35
Joined: 2017-09-12 20:57

Terminal command to get CPU usage?

#1 Post by THX1138b »

Can anyone help me with a console command to get CPU usage? On my Raspberry Pi running Raspbian Stretch I get output like this:

Code: Select all

$ iostat -c
Linux 4.14.34-v7+ (raspberry) 	23/08/18 	_armv7l_	(4 CPU)

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           2.62    0.00    0.30    0.14    0.00   96.93
from iostat but a) this doesn't match what the CPU usage monitor on the taskbar says (right now it's ~70%) and b) I need just a single number (e.g. 70.21 or whatever). Thanks.
antiX 16, Wyse V90L thin client with VIA Eden 32-bit 800 MHz CPU and 1 GB 533 MHz DDR2
Raspberry Pi 3 B and 3 B+, both running Raspbian Stretch

We don't inherit the Earth from our parents; we borrow it from our children.


THX1138b
Posts: 35
Joined: 2017-09-12 20:57

Re: Terminal command to get CPU usage?

#3 Post by THX1138b »

Won't commands that work on Debian also work on Raspbian?
antiX 16, Wyse V90L thin client with VIA Eden 32-bit 800 MHz CPU and 1 GB 533 MHz DDR2
Raspberry Pi 3 B and 3 B+, both running Raspbian Stretch

We don't inherit the Earth from our parents; we borrow it from our children.

arochester
Emeritus
Emeritus
Posts: 2435
Joined: 2010-12-07 19:55
Has thanked: 14 times
Been thanked: 54 times

Re: Terminal command to get CPU usage?

#4 Post by arochester »

Not necessarily.

As I have said before, start with Debian, add something, take something away, change something. It is no longer Debian, it is something else.

As oswaldkelso said some time ago
Something to be aware of: Debian is a core or source distribution. This means there are many Debian-based distributions. THEY ARE NOT DEBIAN. Their information may or may not be useful or safely applied to Debian. Debian has no way of knowing what has been changed on these systems.

THX1138b
Posts: 35
Joined: 2017-09-12 20:57

Re: Terminal command to get CPU usage?

#5 Post by THX1138b »

arochester wrote:Not necessarily.

As I have said before, start with Debian, add something, take something away, change something. It is no longer Debian, it is something else.

As oswaldkelso said some time ago
Something to be aware of: Debian is a core or source distribution. This means there are many Debian-based distributions. THEY ARE NOT DEBIAN. Their information may or may not be useful or safely applied to Debian. Debian has no way of knowing what has been changed on these systems.
Okay, well, this command works in case anyone finds their way here through a search engine in the future:

Code: Select all

top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | gawk '{print $2+$4+$6}
antiX 16, Wyse V90L thin client with VIA Eden 32-bit 800 MHz CPU and 1 GB 533 MHz DDR2
Raspberry Pi 3 B and 3 B+, both running Raspbian Stretch

We don't inherit the Earth from our parents; we borrow it from our children.

User avatar
sunrat
Administrator
Administrator
Posts: 6412
Joined: 2006-08-29 09:12
Location: Melbourne, Australia
Has thanked: 116 times
Been thanked: 462 times

Re: Terminal command to get CPU usage?

#6 Post by sunrat »

THX1138b wrote:
arochester wrote:Okay, well, this command works in case anyone finds their way here through a search engine in the future:

Code: Select all

top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | gawk '{print $2+$4+$6}
That command doesn't work here. Just missing the last character -

Code: Select all

top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | awk '{print $2+$4+$6}'
CPU usage changes every cycle which is probably in the nanoseconds. You can only measure a snapshot of it at the time of measuring. It also has a bit of a quantum effect in that it will be different just because you are measuring it.
I have a Conky which shows it every second and it's never the same 2 seconds in a row unless it's working hard and maxed out. Inside .conkyrc it's just a variable

Code: Select all

CPU1: ${cpu cpu1}%
“ computer users can be divided into 2 categories:
Those who have lost data
...and those who have not lost data YET ”
Remember to BACKUP!

User avatar
oswaldkelso
df -h | grep > 20TiB
df -h | grep > 20TiB
Posts: 1490
Joined: 2005-07-26 23:20
Location: UK
Has thanked: 1 time
Been thanked: 58 times

Re: Terminal command to get CPU usage?

#7 Post by oswaldkelso »

Try this. It's what I have running in my tint2 panel and works on my Dragora system and did on my Debian systems. :twisted:

Code: Select all

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 "CPU:" "%s%.1f%%\n", prefix, 100 - v } '
Good quote that and I stand by it... not sure if it really applies to top, tail and grep though :mrgreen:
Free Software Matters
Ash init durbatulûk, ash init gimbatul,
Ash init thrakatulûk agh burzum-ishi krimpatul.
My oldest used PC: 1999 imac 333Mhz 256MB PPC abandoned by Debian

User avatar
debiman
Posts: 3063
Joined: 2013-03-12 07:18

Re: Terminal command to get CPU usage?

#8 Post by debiman »

^ god, that's ugly.
so many pipes!
i like the averaging though.

i found this online:

Code: Select all

grep '^cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {printf "%.2f%\n", usage}'
advantages: the stats are queried directly with grep, and besides awk no other utilities are required to process the output.

User avatar
Head_on_a_Stick
Posts: 14114
Joined: 2014-06-01 17:46
Location: London, England
Has thanked: 81 times
Been thanked: 132 times

Re: Terminal command to get CPU usage?

#9 Post by Head_on_a_Stick »

debiman wrote:

Code: Select all

grep '^cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {printf "%.2f%\n", usage}'
awk can do searches as well, it is Turing-complete ;)

Code: Select all

awk '/^cpu/{usage=($2+$4)*100/($2+$4+$5)} END {printf "%.2f%\n", usage}' /proc/stat
Bloody interweb... :x
deadbang

User avatar
debiman
Posts: 3063
Joined: 2013-03-12 07:18

Re: Terminal command to get CPU usage?

#10 Post by debiman »

^ better.

however, the command doesn't work :-(
just did a stress test, but it always shows 6.3%.

arzgi
Posts: 1185
Joined: 2008-02-21 17:03
Location: Finland
Been thanked: 31 times

Re: Terminal command to get CPU usage?

#11 Post by arzgi »

debiman wrote:^ better.

however, the command doesn't work :-(
just did a stress test, but it always shows 6.3%.
I did see some variation, from 9.98% to 11,04%, while gkrellm peeked at 100%.

User avatar
Head_on_a_Stick
Posts: 14114
Joined: 2014-06-01 17:46
Location: London, England
Has thanked: 81 times
Been thanked: 132 times

Re: Terminal command to get CPU usage?

#12 Post by Head_on_a_Stick »

deadbang

User avatar
debiman
Posts: 3063
Joined: 2013-03-12 07:18

Re: Terminal command to get CPU usage?

#13 Post by debiman »

if i understand correctly, querying /proc/stat only once cannot show current cpu usage in percent - we need a delta between two reads.

User avatar
Head_on_a_Stick
Posts: 14114
Joined: 2014-06-01 17:46
Location: London, England
Has thanked: 81 times
Been thanked: 132 times

Re: Terminal command to get CPU usage?

#14 Post by Head_on_a_Stick »

^ Looks like it, yes. You could have a peek at top(1)'s code and see how it generates the readout:

http://procps.sourceforge.net/
deadbang

User avatar
debiman
Posts: 3063
Joined: 2013-03-12 07:18

Re: Terminal command to get CPU usage?

#15 Post by debiman »

oh, that bash script is nice enough.
it does the delta, but still no averaging.

i was hacking on it on the weekend, just for fun:

Code: Select all

#!/bin/bash 

delay=1

tput civis
trap 'tput cnorm' EXIT

# sleep as a builtin
for file in /usr/lib/bash/sleep /usr/lib32/bash/sleep /usr/lib64/bash/sleep; do
    [ -r "$file" ] && enable -f "$file" sleep && break
done
# Portable enough?

while :; do
  # Get the first line with aggregate of all CPUs 
  read -r -a cpu_now </proc/stat
  # Get all columns but skip the first (which is the "cpu" string) 
  cpu_sum="${cpu_now[@]:1}" 
  # Replace the column seperator (space) with + 
  cpu_sum="${cpu_sum// /+}"
  # Get the delta between two reads 
  cpu_delta=$((cpu_sum - cpu_last_sum)) 
  # Get the idle time Delta 
  cpu_idle=$((cpu_now[4]- cpu_last[4])) 
  # Calc time spent working 
  cpu_used=$((cpu_delta - cpu_idle)) 
  # Calc percentage 
  cpu_usage=$((100 * cpu_used / cpu_delta)) 

  # Keep this as last for our next read 
  cpu_last=("${cpu_now[@]}") 
  cpu_last_sum=$cpu_sum 

  case $cpu_usage in
    [1-4]?|?) color='' ;;
    [5-7]?) color='\e[33m' ;; # yellow
    [8-9]?|100) color='\e[31m' ;; # red
  esac

  printf "\r\E[0KCPU ${color}%02d%%\E[0m" $cpu_usage 
  
  # Wait a second before the next read 
  sleep "$delay"
done
maybe i can get the averaging in at some point, maybe even make it POSIX compliant (sh instead of bash, no arrays).

User avatar
None1975
df -h | participant
df -h | participant
Posts: 1389
Joined: 2015-11-29 18:23
Location: Russia, Kaliningrad
Has thanked: 45 times
Been thanked: 66 times

Re: Terminal command to get CPU usage?

#16 Post by None1975 »

THX1138b wrote:Can anyone help me with a console command to get CPU usage?
Or would it be easier to use a simple top command?
OS: Debian 12.4 Bookworm / DE: Enlightenment
Debian Wiki | DontBreakDebian, My config files on github

User avatar
oswaldkelso
df -h | grep > 20TiB
df -h | grep > 20TiB
Posts: 1490
Joined: 2005-07-26 23:20
Location: UK
Has thanked: 1 time
Been thanked: 58 times

Re: Terminal command to get CPU usage?

#17 Post by oswaldkelso »

I've been using the above script on one of my machines since seeing it in this thread. It certainly felt snappier and gave similar results to the previous script.

Today however I ran ps_mem I noticed after prolonged use it's memory usage had grown.

Code: Select all

  5.9 MiB + 664.5 KiB =   6.5 MiB	wmaker (2)
 10.5 MiB +   1.4 MiB =  11.9 MiB	wicd-client
 12.6 MiB +   1.7 MiB =  14.2 MiB	Xorg
 15.0 MiB +   1.8 MiB =  16.8 MiB	lilyterm
 20.4 MiB + 175.0 KiB =  20.5 MiB	cpu-usage.sh
 50.6 MiB + 137.0 KiB =  50.7 MiB	weechat-curses
---------------------------------
                        180.1 MiB
=================================

Code: Select all

└> $ uptime
 10:24:24 up 18 days, 12:12,  3 users,  load average: 0.61, 1.12, 1.38
┌—————————(kelsoo)————————<<<<(~) (Thu Sep 13 10:24:24) 
└> $ 
Any ideas?
Free Software Matters
Ash init durbatulûk, ash init gimbatul,
Ash init thrakatulûk agh burzum-ishi krimpatul.
My oldest used PC: 1999 imac 333Mhz 256MB PPC abandoned by Debian

User avatar
Head_on_a_Stick
Posts: 14114
Joined: 2014-06-01 17:46
Location: London, England
Has thanked: 81 times
Been thanked: 132 times

Re: Terminal command to get CPU usage?

#18 Post by Head_on_a_Stick »

oswaldkelso wrote:Any ideas?
Use conky, perhaps?

Or something like slstatus — that consumes about 0.5MiB in my systems, although my maximum uptime tends to be less than a day.
deadbang

User avatar
debiman
Posts: 3063
Joined: 2013-03-12 07:18

Re: Terminal command to get CPU usage?

#19 Post by debiman »

oswaldkelso wrote:
I've been using the above script on one of my machines since seeing it in this thread. It certainly felt snappier and gave similar results to the previous script.

Today however I ran ps_mem I noticed after prolonged use it's memory usage had grown.

Code: Select all

  5.9 MiB + 664.5 KiB =   6.5 MiB	wmaker (2)
 10.5 MiB +   1.4 MiB =  11.9 MiB	wicd-client
 12.6 MiB +   1.7 MiB =  14.2 MiB	Xorg
 15.0 MiB +   1.8 MiB =  16.8 MiB	lilyterm
 20.4 MiB + 175.0 KiB =  20.5 MiB	cpu-usage.sh
 50.6 MiB + 137.0 KiB =  50.7 MiB	weechat-curses
---------------------------------
                        180.1 MiB
=================================
you use the version from that web page, exactly, no changes?

what do the fields in ps_mem output represent? you have heard about "Linux Ate my RAM", yes?

User avatar
oswaldkelso
df -h | grep > 20TiB
df -h | grep > 20TiB
Posts: 1490
Joined: 2005-07-26 23:20
Location: UK
Has thanked: 1 time
Been thanked: 58 times

Re: Terminal command to get CPU usage?

#20 Post by oswaldkelso »

Exactly with no changes. Yes. I know about "Linux Ate my RAM"

I run a lot of old and low end hardware (256MB>3000MB) RAM usage is very noticeable on how well they run.
Free Software Matters
Ash init durbatulûk, ash init gimbatul,
Ash init thrakatulûk agh burzum-ishi krimpatul.
My oldest used PC: 1999 imac 333Mhz 256MB PPC abandoned by Debian

Post Reply