linux下如何得到cpu使用率

cyliao 2007-12-17 03:24:09
linux中,MEM,流量都可以比较好的得到,但CPU的使用率有点麻烦,经过一番测试,把top的源码稍改了一下,可以得到,源码如下:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <fcntl.h>

#define NCPUSTATES 5

static long cp_time[NCPUSTATES];
static long cp_old[NCPUSTATES];
static long cp_diff[NCPUSTATES];
int cpu_states[NCPUSTATES];
char buffer[4096+1];


static inline char *
skip_token(const char *p)
{
while (isspace(*p)) p++;
while (*p && !isspace(*p)) p++;
return (char *)p;
}

long percentages(cnt, out, new, old, diffs)
int cnt;
int *out;
register long *new;
register long *old;
long *diffs;

{
register int i;
register long change;
register long total_change;
register long *dp;
long half_total;

/* initialization */
total_change = 0;
dp = diffs;

/* calculate changes for each state and the overall change */
for (i = 0; i < cnt; i++)
{
if ((change = *new - *old) < 0)
{
/* this only happens when the counter wraps */
change = (int)
((unsigned long)*new-(unsigned long)*old);
}
total_change += (*dp++ = change);
*old++ = *new++;
}

/* avoid divide by zero potential */
if (total_change == 0)
{
total_change = 1;
}

/* calculate percentages based on overall change, rounding up */
half_total = total_change / 2l;
half_total = 0;
for (i = 0; i < cnt; i++)
{
//printf("dd %ld %ld\n",(*diffs* 1000 + half_total),total_change);
*out++ = (int)((*diffs++ * 1000 + half_total) / total_change);
}

/* return the total in case the caller wants to use it */
return(total_change);
}

int main(){
int fd,len;
char *p;
int i;

for(i = 0; i < 4; i++){
cpu_states[i] = 0;
cp_diff[i] = 0;
}

while(1){
fd = open("/proc/stat", O_RDONLY);
len = read(fd, buffer, sizeof(buffer)-1);
close(fd);
buffer[len] = '\0';

p = skip_token(buffer); /* "cpu" */
cp_time[0] = strtoul(p, &p, 0);
cp_time[1] = strtoul(p, &p, 0);
cp_time[2] = strtoul(p, &p, 0);
cp_time[3] = strtoul(p, &p, 0);
cp_time[4] = strtoul(p,&p,0);
//printf("f %ld %ld %ld %ld\n",cp_time[0],cp_time[1],cp_time[2],cp_time[3]);
percentages(NCPUSTATES, cpu_states, cp_time, cp_old, cp_diff);

printf("cpu used:%4.1f nice:%4.1f sys:%4.1f idle:%4.1f iowait:%4.1f\n",cpu_states[0]/10.0,cpu_states[1]/10.0,cpu_states[2]/10.0,cpu_states[3]/10.0,cpu_states[4]/10.0);

sleep(3);


}

}
...全文
928 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
cnchs 2010-11-09
  • 打赏
  • 举报
回复
非常感谢。
realdragon2 2008-10-16
  • 打赏
  • 举报
回复
这个得mark一下~~
nanjingposts 2008-10-15
  • 打赏
  • 举报
回复
我也在做这个,cpu的利用率就是把/proc/stat文件中cpu各部分间隔一个合适的时间,根据对应的时间差算出各个部分占用的时间比例即可。
你说流量比较好取,请问系统的IO数据,就是系统的读写速率等怎么得到?比较迷惑,恳求帮忙,共同提高!谢谢!
qsxiaoyao 2008-10-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jgpwindows 的回复:]
为什么gcc不能编译的
[/Quote]

可以编译并运行。
jgpwindows 2008-10-14
  • 打赏
  • 举报
回复
为什么gcc不能编译的

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧