Issue
I wonder how do I get the percentage of my processor usage from 0% to 100%?
to know how many percent'm using my processor preferably in bash or other methods provided that percentage.
I have this script that I found on google however it is very much imprecisso I tried to make more improvements could not, does anyone know any method to get the percentage of CPU utilization in% 0-100
my script
NUMCPUS=`grep ^proc /proc/cpuinfo | wc -l`; FIRST=`cat /proc/stat | awk '/^cpu / {print $5}'`; sleep 1; SECOND=`cat /proc/stat | awk '/^cpu / {print $5}'`; USED=`echo 2 k 100 $SECOND $FIRST - $NUMCPUS / - p | dc`; echo ${USED}% CPU Usage
Solution
Processor use or utilization is a measurement over time. One way to measure utilization in %
is by computation over two successive reads of /proc/stat
. A simple common bash script to compute the percentage is:
#!/bin/bash
# Read /proc/stat file (for first datapoint)
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
# compute active and total utilizations
cpu_active_prev=$((user+system+nice+softirq+steal))
cpu_total_prev=$((user+system+nice+softirq+steal+idle+iowait))
usleep 50000
# Read /proc/stat file (for second datapoint)
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
# compute active and total utilizations
cpu_active_cur=$((user+system+nice+softirq+steal))
cpu_total_cur=$((user+system+nice+softirq+steal+idle+iowait))
# compute CPU utilization (%)
cpu_util=$((100*( cpu_active_cur-cpu_active_prev ) / (cpu_total_cur-cpu_total_prev) ))
printf " Current CPU Utilization : %s\n" "$cpu_util"
exit 0
use/output:
$ bash procstat-cpu.sh
Current CPU Utilization : 10
output over 5 iterations:
$ ( declare -i cnt=0; while [ "$cnt" -lt 5 ]; do bash procstat-cpu.sh; ((cnt++)); done )
Current CPU Utilization : 20
Current CPU Utilization : 18
Current CPU Utilization : 18
Current CPU Utilization : 18
Current CPU Utilization : 18
Answered By - David C. Rankin Answer Checked By - Terry (WPSolving Volunteer)