2008年6月8日日曜日

FreeBSD上でのCPUの使用率の計測方法

FreeBSDでCPUの使用率をチェックするために, fluxboxのドック用の自作アプリを使っているのだが, 最近 7-stable のソースの更新をしたところ, そのアプリが動かなくなった. 元々, xosview のソースを流用していて, それでは kvm を使って使用率を取得していたが, どうも仕様が変更になったらしい. 試しに, xosview を入れてみるとやはり動かなかった.

そこで, powerd.c のソースを参考にして, sysctl を使ってCPUの使用率を取るように変更した. 簡単に解説すると, まず, 前処理として, Management Information Base (MIB) を取得しておき, 使用率を取る際はその MIB を使って sysctl(3) を使う. プログラムの一部だけだが, 以下のようになった.

#include <sys/resource.h>
#include <sys/types.h>
#include <sys/sysctl.h>

static int cp_time_mib[2];

/* 前処理. 1回だけ行う. */
void preprocess(void){
int len = 2;
if (sysctlnametomib("kern.cp_time", cp_time_mib, &len))
{
perror("lookup kern.cp_time");
exit(1);
}
}

/* CPUの使用率を百分率で返す */
double cpu_getusage(void)
{
long cpu, nice, system, idle, used, total;
long cpu_time[CPUSTATES];
size_t cpu_time_len;

cpu_time_len = sizeof(cpu_time);
if (sysctl(cp_time_mib, 2, cpu_time, &cpu_time_len, NULL, 0))
{
perror("sysctl error");
exit(1);
}

cpu = cpu_time[CP_USER];
nice = cpu_time[CP_NICE];
system = cpu_time[CP_SYS];
idle = cpu_time[CP_IDLE];

used = cpu + nice + system;
total = used + idle;
return 100.0 * used / (double) total;
}