linux cpu usage percentage code example

Example 1: linux check cpu usage

lscpu

# Or
cat /proc/cpuinfo

Example 2: get current cpu utilization in percentage linux

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

Example 3: get current cpu utilization in percentage linux

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

Example 4: how to set cpu usage to 100% linux

$ sudo cpulimit --pid 17918 --limit 50  

Process 17918 detected