리눅스 CPU 사용률 계산하는 법
조회 5,802 · 댓글 1
1)
2)
3)
4)
5)
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
2)
top -bn1 | grep "Cpu(s)" | \
sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
awk '{print 100 - $1"%"}'
3)
mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 - $ 12}'a
4)
mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
5)
mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { print 100 - $field }'WHAT IS CPU USAGE ANYWAY?
CPU Usage is a picture of how the processors in your machine (real or virtual) are being utilized.
In this context, a single CPU refers to a single (possibly virtualized) hardware hyper-thread. Remember that there might be multiple physical processors in a machine, each with multiple cores, and each core with multiple hyperthreads. In Linux, the hyperthread is the most granular, independently schedulable execution unit. This is the “single CPU”.
Now imagine someone taking a look at all the CPUs every 1/100th of a second, and noting down what type of task each one is executing. There aren’t that many types of tasks (see next section). For each type of task a counter is maintained, so that while sampling if you see that a CPU is executing a particular task type, that counter is incremented. If a CPU executes user code for 1 second, it’s user-code-counter will get incremented by 100.
These counters are maintained by the kernel itself, and can be read from the file /proc/stat (more below).
Note: Technically the magic number 1/100 may be different for your system – you should really be using the value of sysconf(_SC_CLK_TCK) instead.
CPU Usage is a picture of how the processors in your machine (real or virtual) are being utilized.
In this context, a single CPU refers to a single (possibly virtualized) hardware hyper-thread. Remember that there might be multiple physical processors in a machine, each with multiple cores, and each core with multiple hyperthreads. In Linux, the hyperthread is the most granular, independently schedulable execution unit. This is the “single CPU”.
Now imagine someone taking a look at all the CPUs every 1/100th of a second, and noting down what type of task each one is executing. There aren’t that many types of tasks (see next section). For each type of task a counter is maintained, so that while sampling if you see that a CPU is executing a particular task type, that counter is incremented. If a CPU executes user code for 1 second, it’s user-code-counter will get incremented by 100.
These counters are maintained by the kernel itself, and can be read from the file /proc/stat (more below).
Note: Technically the magic number 1/100 may be different for your system – you should really be using the value of sysconf(_SC_CLK_TCK) instead.
로그인 후 답글을 남길 수 있습니다.