当前位置: 技术问答>linux和unix
LINUX如何获得当前CPU的占用率?
来源: 互联网 发布时间:2015-05-15
本文导语: 除了TOP命令可以查看CPU的占用率外 1.有实时记录CPU占用情况的日志文件吗? 2.有其它命令可以获得吗? 3.有底层的API函数可以调用吗? (因当前用一个BUSYBOX命令集,其中的TOP命令无法加入参数。而程序需要实时读取...
除了TOP命令可以查看CPU的占用率外
1.有实时记录CPU占用情况的日志文件吗?
2.有其它命令可以获得吗?
3.有底层的API函数可以调用吗?
(因当前用一个BUSYBOX命令集,其中的TOP命令无法加入参数。而程序需要实时读取当前CPU的占用率)
1.有实时记录CPU占用情况的日志文件吗?
2.有其它命令可以获得吗?
3.有底层的API函数可以调用吗?
(因当前用一个BUSYBOX命令集,其中的TOP命令无法加入参数。而程序需要实时读取当前CPU的占用率)
|
struct CPU_USAGE
{
unsigned long cpu_user;
unsigned long cpu_sys;
unsigned long cpu_nice;
unsigned long cpu_idle;
};
double Get_Cpu_Use_Rate( const struct CPU_USAGE *cur, const struct CPU_USAGE *old )
{
double user, sys, nice, idle, total;
double use_rate;
user = (double)(cur->cpu_user - old->cpu_user);
sys = (double)(cur->cpu_sys - old->cpu_sys);
nice = (double)(cur->cpu_nice - old->cpu_nice);
idle = (double)(cur->cpu_idle - old->cpu_idle);
total = user + sys + nice + idle;
use_rate = ( 1 - idle / total ) * 100;
return use_rate;
}
double Get_Cpu_Free_Rate( const struct CPU_USAGE *cur, const struct CPU_USAGE *old )
{
double user, sys, nice, idle, total;
double free_rate;
user = (double)(cur->cpu_user - old->cpu_user);
sys = (double)(cur->cpu_sys - old->cpu_sys);
nice = (double)(cur->cpu_nice - old->cpu_nice);
idle = (double)(cur->cpu_idle - old->cpu_idle);
total = user + sys + nice + idle;
free_rate = ( idle / total ) * 100;
return free_rate;
}
struct CPU_USAGE 结构中的数据是从/proc/stat中获得的,需要你自己去读文件。
{
unsigned long cpu_user;
unsigned long cpu_sys;
unsigned long cpu_nice;
unsigned long cpu_idle;
};
double Get_Cpu_Use_Rate( const struct CPU_USAGE *cur, const struct CPU_USAGE *old )
{
double user, sys, nice, idle, total;
double use_rate;
user = (double)(cur->cpu_user - old->cpu_user);
sys = (double)(cur->cpu_sys - old->cpu_sys);
nice = (double)(cur->cpu_nice - old->cpu_nice);
idle = (double)(cur->cpu_idle - old->cpu_idle);
total = user + sys + nice + idle;
use_rate = ( 1 - idle / total ) * 100;
return use_rate;
}
double Get_Cpu_Free_Rate( const struct CPU_USAGE *cur, const struct CPU_USAGE *old )
{
double user, sys, nice, idle, total;
double free_rate;
user = (double)(cur->cpu_user - old->cpu_user);
sys = (double)(cur->cpu_sys - old->cpu_sys);
nice = (double)(cur->cpu_nice - old->cpu_nice);
idle = (double)(cur->cpu_idle - old->cpu_idle);
total = user + sys + nice + idle;
free_rate = ( idle / total ) * 100;
return free_rate;
}
struct CPU_USAGE 结构中的数据是从/proc/stat中获得的,需要你自己去读文件。
|
纠正一下:vmstat 1