LinuxのCPU使用率を計測するには、top
などのコマンドが使えますが、
高機能がゆえに、測定コマンド自身が少し重いと感じていました。
単に、CPU使用率を測定したいのであれば、/proc/stat
を一定間隔で取得することで算出できます。
CプログラムやRubyスクリプトを紹介しているブログもあり、参考になります。
/proc/stat
の値の意味は、naoyaさんの記事も勉強になります。
コマンド cpustat を作りました
個人的に、AMPで動いているシステムでCPU使用率を図りたいケースがあり、
かつ、sar
とかも簡単にインストールできない環境だったので、自作しました。
使い方
使い方は、以下のヘルプ内容の通り。
$ ./cpustat.exe -h Usage: ./cpustat.exe [OPTION]... Options: -d, --delay=SEC delay-time interval -c, --cpumask=MASK specify cpu-mask -a, --accumulation accumulate each cpus if cpu-mask is specified -h, --help display this help
オプション指定なしであれば、CPU全体の使用率を1秒毎に標準出力します。
./cpustat.exe delay = 1.000000000 sec date time user% nice% sys% idle% 2015/07/08 00:10:50.471471 0.51% 0.00% 0.79% 98.26% 2015/07/08 00:10:51.473531 0.00% 0.00% 0.00% 100.00% 2015/07/08 00:10:52.475964 0.00% 0.00% 0.00% 100.00% 2015/07/08 00:10:53.509681 0.00% 0.00% 0.00% 100.00% 2015/07/08 00:10:54.515131 0.00% 0.00% 0.24% 99.75% ( Ctrl + c で終了 )
インターバル変更
オプション -d
で、測定周期を変更できます。1秒未満も指定できます。
もちろんオーバーヘッドの割合が大きくなるので精度(?)は落ちると思いますが。
$ ./cpustat.exe -d 0.2 delay = 0.200000000 sec date time user% nice% sys% idle% 2015/07/08 00:12:24.737498 0.48% 0.00% 0.76% 98.33% 2015/07/08 00:12:24.941880 0.00% 0.00% 1.21% 98.78% 2015/07/08 00:12:25.144380 0.00% 0.00% 0.00% 100.00% 2015/07/08 00:12:25.346361 0.00% 0.00% 0.00% 100.00%
CPUマスク指定
オプション -c
で測定対象のCPUのマスク値を指定できます。
例えば、CPU#2とCPU#3を指定する場合は、0x0C (0000 1100)とします。
$ ./cpustat.exe -c 0c cpumask = c delay = 1.000000000 sec cpu# date time user% nice% sys% idle% cpu2 2015/07/08 00:14:56.836423 0.31% 0.00% 0.63% 98.78% cpu3 2015/07/08 00:14:56.836807 0.41% 0.00% 0.68% 98.60% cpu2 2015/07/08 00:14:57.838844 0.00% 0.00% 1.00% 99.00% cpu3 2015/07/08 00:14:57.839269 0.00% 0.00% 0.00% 100.00% cpu2 2015/07/08 00:14:58.841128 0.00% 0.00% 0.00% 100.00% cpu3 2015/07/08 00:14:58.841340 0.00% 0.00% 0.00% 100.00%
CPUマスク指定(累積)
さらに、-a
オプションを指定した場合は、
CPUマスク指定した対象CPUの累積値からCPU使用率を算出します。
$ ./cpustat.exe -c 0c -a cpumask = c delay = 1.000000000 sec date time user% nice% sys% idle% 2015/07/08 00:16:04.464295 0.35% 0.00% 0.63% 98.72% 2015/07/08 00:16:05.466384 0.00% 0.00% 0.50% 99.50% 2015/07/08 00:16:06.472750 0.00% 0.00% 0.00% 100.00% 2015/07/08 00:16:07.475505 0.00% 0.00% 0.49% 99.50%
少々荒い作りですが、まぁ割と軽量に動くと思います。満足。