Linux下如何得到某一进程序CPU占用率????

zxk105 2006-06-05 04:19:10
请问Linux下有没有什么API可以查看某个进程所占的CPU占用率????
那ps查看到的CPU占用率一样。
...全文
550 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
limlzm 2006-06-07
  • 打赏
  • 举报
回复
mark
zengwh 2006-06-07
  • 打赏
  • 举报
回复
px -aux
fytzzh 2006-06-07
  • 打赏
  • 举报
回复
linux 自带的命令也是读/proc。
网上有个libproc的库可以使用
ghtsao 2006-06-06
  • 打赏
  • 举报
回复
正好做过点这个,给你参考一下,恕未整理:

char buf[64];
sprintf(buf,"/proc/%d/stat",pid);
FILE* fid = fopen(buf,"r");
if(fid){
fscanf(fid,"%d %s %c %d %d %d %d %d %lu %lu "
"%lu %lu %lu %lu %lu %ld %ld %ld %ld %ld "
"%ld %ld %lu %lu %ld %lu %lu %lu %lu %lu",
&pstat[0],buf,&pstat[2],&pstat[3],&pstat[4],&pstat[5],&pstat[6],&pstat[7],
&pstat[8],&pstat[9],&pstat[10],&pstat[11],&pstat[12],&pstat[13],&pstat[14],&pstat[15],
&pstat[16],&pstat[17],&pstat[18],&pstat[19],&pstat[20],&pstat[21],&pstat[22],&pstat[23],
&pstat[24],&pstat[25],&pstat[26],&pstat[27],&pstat[28],&pstat[29],&pstat[30]);
fclose(fid);

。。。。。

ut = pstat[13];
st = pstat[14];
cut = pstat[15];
cst = pstat[16];

。。。。。
ts = time(NULL) - lasttime;
百分比=(ut+st-sut-sst)/ts
eqxu 2006-06-05
  • 打赏
  • 举报
回复
top
然后Shift+m
iohui 2006-06-05
  • 打赏
  • 举报
回复
在shell里用top命令 ^_^
hundlom 2006-06-05
  • 打赏
  • 举报
回复
一般情况下是读/proc目录下的内容。
x86 2006-06-05
  • 打赏
  • 举报
回复
/proc下每个进程有一个目录,目录下的stat文件可以得到关于该进程的信息,比如:
# cat /proc/2122/stat
2122 (sshd) S 6599 2122 2122 0 -1 8448 1110 217 0 1 20 3 12 0 15 0 1 0 242306177 8482816 592 4294967295 134512640 134795532 3221224656 3221220240 4294960144 0 0 4096 73728 0 0 0 17 0 0 0

具体每一项的内容可以看man:
man 5 proc

cpu的占用率似乎并不能直接得到,你需要自己去计算,我猜想ps的做法是从/proc得到所有进程的信息,通过每个进程的运行时间,可以计算出某个进程的占用率

23,121

社区成员

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

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