您的位置:首页 > 运维架构 > Linux

Linux下内存占用和CPU占用的计算

2015-08-25 10:27 417 查看
->使用free命令查看内存使用情况:

1.echo 3 > /proc/sys/vm/drop_caches

2.free

或者使用cat /proc/yourpid/status 来查看对应pid的内存占用(VmRSS为当前值,VmHWM为峰值)

(注:linux下的malloc申请100mb内存,并不会马上得到100mb,只会预分配一部分,用到时才另外分配)

->使用top -n 1查看进程的CPU占用情况。

或者使用以下方法计算:

FILE *fp = fopen("/proc/stat", "r");
if (fp) {
char name[64] = { 0 };
char buffer[1024] = { 0 };
static int user0 = 0, total0 = 0;
int user1, nice, sys, idle, iowait, irq, softirq, total1 = 0;

fgets(buffer, sizeof(buffer), fp);
sscanf(buffer, "%s %d %d %d %d %d %d %d", name, &user1, &nice, &sys,
&idle, &iowait, &irq, &softirq);
total1 = user1 + nice + sys + iowait + irq + softirq + idle;
if (total1 != total0)
m_iCpuPercent = ((user1 - user0) * 100)/ (double) (total1 - total0);
else
m_iCpuPercent = 0;
user0 = user1;
total0 = total1;
fclose(fp);
} else {
fprintf(stderr, "fopen failed:%s\n", strerror(errno));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: