Sunday, May 19, 2024
16
rated 0 times [  16] [ 0]  / answers: 1 / hits: 121336  / 3 Years ago, wed, october 13, 2021, 6:24:33

I want to see CPU usage.

I used this command :



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


But it returns 100%.

What's the correct way?


More From » command-line

 Answers
6

To get cpu usage, best way is to read /proc/stat file. See man 5 proc for more help.



There is a useful script written by Paul Colby i found here



#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)

PREV_TOTAL=0
PREV_IDLE=0

while true; do

CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
unset CPU[0] # Discard the "cpu" prefix.
IDLE=${CPU[4]} # Get the idle CPU time.

# Calculate the total CPU time.
TOTAL=0

for VALUE in "${CPU[@]:0:4}"; do
let "TOTAL=$TOTAL+$VALUE"
done

# Calculate the CPU usage since we last checked.
let "DIFF_IDLE=$IDLE-$PREV_IDLE"
let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
echo -en "
CPU: $DIFF_USAGE% "

# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"

# Wait before checking again.
sleep 1
done


save it to cpu_usage, add execute permission chmod +x cpu_usage and run:



./cpu_usage


to stop the script, hit Ctrl+c


[#25927] Friday, October 15, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hamostic

Total Points: 403
Total Questions: 142
Total Answers: 112

Location: Iceland
Member since Sat, Sep 17, 2022
2 Years ago
;