编程获取linux的CPU使用率内存占用率

Linux下提供top、ps命令查看当前cpu、mem使用情况,简要介绍如下:

一、使用ps查看进程的资源占用

ps -aux

查看进程信息时,第三列就是CPU占用。

[[email protected] utx86]# ps -aux | grep my_process

Warning: bad syntax, perhaps a bogus ‘-‘? See /usr/share/doc/procps-3.2.7/FAQ

root   14415  3.4  0.9   37436  20328  pts/12   SL+  14:18   0:05 ./my_process

root   14464  0.0   0.0   3852   572    pts/3    S+   14:20   0:00 grep my_process

每一列含义如下

USER   PID   %CPU %MEM  VSZ  RSS TTY  STAT   START  TIME   COMMAND

即my_process进程当前占用cpu 3.4%, 内存0.9%

二、top动态查看系统负荷

top -n 1

显示后退出

[[email protected] utx86]# top -n 1

top - 14:23:20 up  5:14, 14 users,  load average: 0.00, 0.04, 0.01

Tasks: 183 total,   1 running, 181 sleeping,   1 stopped,   0 zombie

Cpu(s):  1.8%us,  1.4%sy,  0.0%ni, 95.8%id,  0.7%wa,  0.1%hi,  0.2%si,  0.0%st

Mem:   2066240k total,  1507316k used,   558924k free,   190472k buffers

Swap:  2031608k total,       88k used,  2031520k free,  1087184k cached

1、获取cpu占用情况

[[email protected] utx86]# top -n 1 |grep Cpu

Cpu(s):  1.9%us,  1.3%sy,  0.0%ni, 95.9%id,  0.6%wa,  0.1%hi,  0.2%si,  0.0%st

解释:1.9%us是用户占用cpu情况

1.3%sy,是系统占用cpu情况

得到具体列的值:

[[email protected] utx86]# top -n 1 |grep Cpu | cut -d "," -f 1 | cut -d ":" -f 2

1.9%us

[[email protected] utx86]# top -n 1 |grep Cpu | cut -d "," -f 2

1.3%sy

2、获得内存占用情况

[[email protected] utx86]# top -n 1 |grep Mem

Mem:   2066240k total,  1515784k used,   550456k free,   195336k buffers

获得内存情况指定列

[[email protected] c++_zp]# top -n 1 |grep Mem | cut -d "," -f 1 | cut -d ":" -f 2

2066240k total

[[email protected] c++_zp]# top -n 1 |grep Mem | cut -d "," -f 2

1585676k used

三、编程实现

现在可以通过程序将cpu使用率、内存使用情况保存到文件中

// test.cpp

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

int main()

{

system("top -n 1 |grep Cpu | cut -d \",\" -f 1 | cut -d \":\" -f 2 >cpu.txt");

system("top -n 1 |grep Cpu | cut -d \",\" -f 2 >>cpu.txt");

system("top -n 1 |grep Mem | cut -d \",\" -f 1 | cut -d \":\" -f 2 >>cpu.txt");

system("top -n 1 |grep Mem | cut -d \",\" -f 2 >>cpu.txt");

return 0;

}

编译、运行:

[[email protected] study]# g++ test.cpp

[[email protected] study]# ./a.out

[[email protected] study]# cat cpu.txt

2.1%us

1.5%sy

2066240k total

1619784k used

四、硬盘使用率编程实现

1.硬盘使用率 命令df -lh

2.程序实现,调用statfs

int statfs(const char *path, struct statfs *buf);

int fstatfs(int fd, struct statfs *buf);

struct statfs {

long    f_type;    /* type of filesystem (see below) */

long    f_bsize;    /* optimal transfer block size */

long    f_blocks;  /* total data blocks in file system */

long    f_bfree;    /* free blocks in fs */

long    f_bavail;  /* free blocks avail to non-superuser */

long    f_files;    /* total file nodes in file system */

long    f_ffree;    /* free file nodes in fs */

fsid_t  f_fsid;    /* file system id */

long    f_namelen;  /* maximum length of filenames */

};

int fstatvfs(int fildes, struct statvfs *buf);

int statvfs(const char *restrict path, struct statvfs *restrict buf);

struct statvfs {

unsigned long  f_bsize;    /* file system block size */

unsigned long  f_frsize;  /* fragment size */

fsblkcnt_t    f_blocks;  /* size of fs in f_frsize units */

fsblkcnt_t    f_bfree;    /* # free blocks */

fsblkcnt_t    f_bavail;  /* # free blocks for non-root */

fsfilcnt_t    f_files;    /* # inodes */

fsfilcnt_t    f_ffree;    /* # free inodes */

fsfilcnt_t    f_favail;  /* # free inodes for non-root */

unsigned long  f_fsid;    /* file system id */

unsigned long  f_flag;    /* mount flags */

unsigned long  f_namemax;  /* maximum filename length */

};

#include <sys/vfs.h>

#include <sys/statvfs.h>

#include <string.h>

#include <stdlib.h>

#include <stdio.h>

int gethd(char *path);

int main()

{

char buf[256],*ptr;

FILE *file;

while(1)

{

file=fopen("/etc/fstab","r");

if(!file)return;

memset(buf,0,sizeof(buf));

while(fgets(buf,sizeof(buf),file))

{

ptr=strtok(buf," ");

if(ptr&&((strncmp(ptr,"/dev",4)==0)))

{

ptr=strtok(NULL," ");

gethd(ptr);

}

}

fclose(file);

sleep(2);

}

}

int gethd(char *path)

{

struct statvfs stat1;

statvfs(path,&stat1);

if(stat1.f_flag)

printf("%s total=%dK free=%dK %0.1f%%

\n",path,stat1.f_bsize*stat1.f_blocks/1024,stat1.f_bsize*stat1.f_bfree/1024,

((float)stat1.f_blocks-(float)stat1.f_bfree)/(float)stat1.f_blocks*100);

}

shell

监视磁盘hda1

#!/bin/sh

# disk_mon

# monitor the disk space

# get percent column and strip off header row from df

LOOK_OUT=0

until [ "$LOOK_OUT" -gt "90" ]

do

LOOK_OUT=`df | grep /hda1 | awk ‘{print $5}‘ | sed ‘s/%//g‘`

echo $LOOK_OUT%

sleep 1

done

echo "Disk hda1 is nearly full!"

hdtest.sh

#!/bin/ksh

#检测硬盘剩余空间并警告的shell&nbspV050921

#简单说明: 可由root用户将此脚本加入crontab,启动时间一般最好设为每天营业前,当此脚本启动时如检测到已用硬盘空间超过指定范围,则将hdwarning.sh脚本拷贝到指定用户根目录下;否则将删除指定用户的目录下的hdwarning.sh脚本.

usedhd=80           #自定义超限已用硬盘空间大小比例,默认为80%

test "$1" &&&nbspuserdir=$1 ||&nbspuserdir=/usr/scabs  #前台用户的目录(默认设为统版用户),也可在调用此脚本时加上指定前台用户的目录参数

hdwarning=$(df&nbsp-v |sed 1d;s/.$//;s/\/dev\///|awk $6>‘"$usedhd"‘ {print $2," = ",$6"%"})

test "$hdwarning" && {&nbspcp /usr/bin/hdwarning.sh ${userdir}/hdwarning.sh  \

> ${userdir}/hdwarning.log &nbspchmod&nbsp777 ${userdir}/hdwarning.sh ${userdir}/hdwarning.log  } \

|| {&nbsprm ${userdir}/hdwarning.sh&nbsp2>/dev/null  \

mv ${userdir}/hdwarning.log ${userdir}/hdwarning.log.bak&nbsp2>/dev/null  }

hdwarning.sh

#!/bin/ksh

#检测硬盘剩余空间并警告的shell&nbspV050921

#增加当超标时,只在预先指定的前N位预先的指定用户登录时才显示提示信息,

#即只有这前面N位用户才有可能及时反馈,避免当超标时接到过多的前台反馈电话&nbspV050923

#请先编辑指定用户根下的&nbsp.profile ,在最后追加一行

# &nbsptest&nbsp-x&nbsphdwarning.sh && &nbsp./hdwarning.sh

#若.profile最后已加入了自启动专用程序命令行,则请在此行前面插入上述行

#简单说明: 当指定用户登录后,若当前目录中hdwarning.sh脚本存在(一般此

#时硬盘已用空间已经超标),则运行此脚本,并在屏幕显示警告信息,此时终端

#操作人员应该及时将此信息把馈给预先指定的部门或预先指定的管理人员,

#以便作相应的处理.若未超标或已清理磁盘文件并达标,则将删除脚本自身

#hdwarning.sh(取消登录时的检测和警告信息)

usedhd=80               #自定义超限已用硬盘空间大小比例,默认为80%

loginnum=10             #自定义最初登录反馈的用户数,默认为前&nbsp10 位

name="运维部"           #接受反馈的部门或管理人员

tel="2113714&nbsp2110394"   #接受反馈的部门或管理人员的联系方式或电话

test "$1" &&&nbspuserdir=$1 ||&nbspuserdir=/usr/scabs  #前台用户的目录(默认设为统版用户),也可在调用此

#脚本时加上指定前台用户的目录参数

hdwaring()

{&nbspttyname=$(tty)

echo ${ttyname##*

shell cpu====================================================================:

/proc目路下的内存文件系统映射了系统的运行时的一些信息,包括进程列表,

内存信息,CPU使用情况,还有网络等等

所以可以通过读/proc下的文件来实现统计信息的获取

但是,要注意的时不同的版本,将/proc下的每个文件中的类容会有一些差别,每一个项代表什么要自己分析,最好根据top的输出去分析

然后就可以通过shell教本或者C取得CPU使用率

比如:

我的机子是AS4(Kernel 2.6.9-5)

cat /proc/stat

cpu  1047871 11079 394341 1157538880 4909104 1945 61338

cpu0 352894 2950 157917 290318045 109839 0 49564

cpu1 234860 1978 115148 288108962 2522748 1028 6391

cpu2 106253 1674 52273 288601985 2225180 909 2839

cpu3 353863 4477 69001 290509888 51337 6 2543

intr 3021292348 2939335896 720 0 12 12 0 7 2 1 0 0 0 1951 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7217173 0 0 0 0 0 0 0 30 0 0 0 0 0 0 0 74736544 0 0 0 0 0 0 0 0
0 0 0 0 0

ctxt 379682110

btime 1158715143

processes 603543

procs_running 1

procs_blocked 0

然后就可以自己计算了

  1. #########GetCPU.sh
  2. ######Author:duanjigang
  3. #!/bin/sh
  4. while true
  5. do
  6. awk  ‘$1=="cpu"{Total=$2+$3+$4+$5+$6+$7;print "Free: " $5/Total*100"%
  7. " " Used: " (Total-$5)*100/Total"%"}‘ </proc/stat
  8. sleep 1
  9. done

复制代码

#./GetCPU.sh

Free: 99.4532% Used: 0.546814%

Free: 99.4532% Used: 0.546813%

Free: 99.4532% Used: 0.546813%

Free: 99.4532% Used: 0.546813%

这样应该可以的

shell cpu MEM====================================================================:

(1):取CPU使用率

机器:LinuxAS4 2.6.9-5.ELsmp (不通版本的内核会有差异的)

  1. #cpu.sh-to get the utilization of every cpu
  2. #author:duanjigang<2006/12/28>
  3. #!/bin/sh
  4. awk ‘$0 ~/cpu[0-9]/‘ /proc/stat  | while read line
  5. do
  6. echo "$line" | awk ‘{total=$2+$3+$4+$5+$6+$7+$8;free=$5;\
  7. print$1" Free "free/total*100"%",\
  8. "Used " (total-free)/total*100"%"}‘
  9. done

复制代码

#chmod +x cpu.sh

#./cpu.sh

cpu0 Free 99.7804% Used 0.219622%

cpu1 Free 99.8515% Used 0.148521%

cpu2 Free 99.6632% Used 0.336765%

cpu3 Free 99.6241% Used 0.375855%

(2)网络流量情况

  1. #if.sh-to get the network flow of each interface
  2. #for my beloved ning
  3. #author:duanjigang<2006/12/28>
  4. #!/bin/sh
  5. echo "name    ByteRec   PackRec   ByteTran   PackTran"
  6. awk   ‘ NR>2‘ /proc/net/dev  | while read line
  7. do
  8. echo "$line" | awk -F ‘:‘ ‘{print "  "$1"  " $2}‘ |\
  9. awk ‘{print $1"   "$2 "    "$3"   "$10"  "$11}‘
  10. done

复制代码

#./if.sh

name    ByteRec   PackRec   ByteTran   PackTran

lo   2386061    17568   2386061  17568

eth0   1159936483    150753251   190980687  991835

eth1   0    0   0  0

sit0   0    0   0  0

(3):端口情况

http://bbs.chinaunix.net/viewthread.php?tid=864757&highlight=duanjigang

(4)至于内存

cat /proc/meminfo | grep "MemTotal"

cat /rpco/meninfo  | grep "MemFree"

就可以了吧

计算内存利用率需要从/proc/meminfo文件中取相应数据,文件内容如下:

MemTotal:      1024008 kB

MemFree:         18448 kB

Buffers:         12664 kB

Cached:         282500 kB

SwapCached:        716 kB

Active:         816124 kB

Inactive:        52516 kB

HighTotal:      122500 kB

HighFree:          304 kB

… …

MemTotal数值表示内存总量,MemFree数值表示空余数量。

所以内存的即时利用率计算公式

(MemTotal - MemFree)/ MemTotal

安装上篇文章的原则,使用C语言写了一段程序来计算CPU和内存利用率:

/*************************************************************
le:        statusinfo.c
 *
 *    @brief:        从linux系统获取cpu及内存使用情况
 *
 *    @version    1.0
 *
 ***************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct PACKED         //定义一个cpu occupy的结构体
{
	char name[20];      //定义一个char类型的数组名name有20个元素
	unsigned int user; //定义一个无符号的int类型的user
	unsigned int nice; //定义一个无符号的int类型的nice
	unsigned int system;//定义一个无符号的int类型的system
	unsigned int idle; //定义一个无符号的int类型的idle
	unsigned int lowait;
	unsigned int irq;
	unsigned int softirq;
}CPU_OCCUPY;

typedef struct __MEM
{
//	unsigned char name[20];
	float total;
	float free;
	}MEM;

int get_meminfo()
{
	MEM meminfo;
	memset(&meminfo,0x00,sizeof(MEM));
	FILE* fp = fopen("/proc/meminfo","r");

	if(fp == NULL)
	{
		printf("Can not open file\r\n");
		return 0;
	}

	char buf[64];
	char name[32];
	memset(buf,0x00,sizeof(buf));
	fgets(buf,sizeof(buf),fp);
	sscanf(buf,"%s %f %s",name,&meminfo.total,name);
	memset(buf,0x00,sizeof(buf));
	fgets(buf,sizeof(buf),fp);
	sscanf(buf,"%s %f %s",name,&meminfo.free,name);
	printf("buf is %s  name is %s %f\r\n",buf,name,meminfo.free);
	float temp;

	sscanf(buf,"%s			%f %s",name,&temp,name);
	printf("temp is %f \r\n",temp);
	double rate = (meminfo.total - meminfo.free)/meminfo.total;
	printf("%f  %f	rate is %f\r\n",meminfo.total,meminfo.free,rate);
	fclose(fp);
	return 1;
}

int cal_cpuoccupy (CPU_OCCUPY *o, CPU_OCCUPY *n)
{
	unsigned long od, nd;
	unsigned long id, sd;
	double cpu_use = 0;   

	od = (unsigned long) (o->user + o->nice + o->system +o->idle + o->lowait + o->irq + o->softirq);//第一次(用户+优先级+系统+空闲)的时间再赋给od
	nd = (unsigned long) (n->user + n->nice + n->system +n->idle + n->lowait + n->irq + n->softirq);//第二次(用户+优先级+系统+空闲)的时间再赋给od

	double sum = nd - od;
	double idle = n->idle - o->idle;
	cpu_use = idle/sum;

	printf("%f\r\n",cpu_use);

	idle = n->user + n->system + n->nice -o->user - o->system- o->nice;
	cpu_use = idle/sum;

	printf("%f\r\n",cpu_use);
	return 0;
}

void get_cpuoccupy (CPU_OCCUPY *cpust) //对无类型get函数含有一个形参结构体类弄的指针O
{
	FILE *fd;
	int n;
	char buff[256];
	CPU_OCCUPY *cpu_occupy;
	cpu_occupy=cpust;

	fd = fopen ("/proc/stat", "r");
	fgets (buff, sizeof(buff), fd);
	printf("%s\r\n",buff);
	sscanf (buff, "%s %u %u %u %u %u %u %u", cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle,&cpu_occupy->lowait,&cpu_occupy->irq,&cpu_occupy->softirq);
	printf("%s %u %u %u %u %u %u %u\r\n", cpu_occupy->name,cpu_occupy->user, cpu_occupy->nice,cpu_occupy->system, cpu_occupy->idle,cpu_occupy->lowait,cpu_occupy->irq,cpu_occupy->softirq);
	printf("%s %u\r\n", cpu_occupy->name,cpu_occupy->user);
	fclose(fd);
}

int main()
{
	CPU_OCCUPY cpu_stat1;
	CPU_OCCUPY cpu_stat2;
	MEM_OCCUPY mem_stat;
	int cpu;
	//第一次获取cpu使用情况
	get_cpuoccupy((CPU_OCCUPY *)&cpu_stat1);
	sleep(10);

	//第二次获取cpu使用情况
	get_cpuoccupy((CPU_OCCUPY *)&cpu_stat2);

	//计算cpu使用率
	cpu = cal_cpuoccupy ((CPU_OCCUPY *)&cpu_stat1, (CPU_OCCUPY *)&cpu_stat2);
	printf("%d \r\n",cpu);
	//获取内存
	get_meminfo();
	return 0;
}
时间: 2024-08-07 01:01:20

编程获取linux的CPU使用率内存占用率的相关文章

linux系统cpu和内存占用率

1.top 使用权限:所有使用者 使用方式:top [-] [d delay] [q] [c] [S] [s] [i] [n] [b] 说明:即时显示process的动态 d :改变显示的更新速度,或是在交谈式指令列( interactive command)按s q :没有任何延迟的显示速度,如果使用者是有superuser的权限,则top将会以最高的优先序执行 c :切换显示模式,共有两种模式,一是只显示执行档的名称,另一种是显示完整的路径与名称S :累积模式,会将己完成或消失的子行程( d

编程实现获取linux服务器cpu、内存和磁盘使用率

proc文件系统介绍 /proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间.它以文件系统的方式为内核与进程提供通信的接口.用户和应用程序可以通过/proc得到系统的信息,并可以改变内核的某些参数.由于系统的信息,如进程,是动态改变的,所以用户或应用程序读取/proc目录中的文件时,proc文件系统是动态从系统内核读出所需信息并提交的. /proc目录中有一些以数字命名的目录,它们是进程目录.系统中当前运行的每一个进程在/proc下都对应一个以进程号为目录名的目录/proc/pi

Java获取Linux系统cpu使用率

原文:http://www.open-open.com/code/view/1426152165201 import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Li

linux ps命令,查看某进程cpu和内存占用率情况, linux ps命令,查看进程cpu和内存占用率排序。 不指定

背景:有时需要单看某个进程的CPU及占用情况,有时需要看整体进程的一个占用情况.一. linux ps命令,查看某进程cpu和内存占用率情况[[email protected] vhost]# ps auxUSER       PID  %CPU    %MEM    VSZ   RSS TTY      STAT    START   TIME COMMAND解释:linux 下的ps命令USER 进程运行用户PID    进程编号%CPU 进程的cpu占用率%MEM 进程的内存占用率VSZ

编程获取linux的CPU使用的内存使用情况

Linux可用下top.ps命令检查当前的cpu.mem用法.下面简单的例子: 一.采用ps查看资源消耗的过程 ps -aux 当您查看进程信息,第三列是CPU入住. [[email protected] utx86]# ps -aux | grep my_process Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.7/FAQ root   14415  3.4  0.9   37436  203

Linux 下用管道执行 ps aux | grep 进程ID 来获取CPU与内存占用率

#include <stdio.h> #include <unistd.h>   int main() {     char caStdOutLine[1024]; // ps 命令的标准输出中的一行信息     char* pcTmp = NULL;      // 指向以空格拆分后的字符串       char caSelfPID[10];      // 自身进程的PID字符串     char caPSCmd[24];        // "ps aux | gr

IIS解决CPU和内存占用率过高的问题

发现进程中的w3wp占用率过高. 经过查询,发现如下: w3wp.exe是在IIS(因特网信息服务器)与应用程序池相关联的一个进程,如果你有多个应用程序池,就会有对应的多个w3wp.exe的进程实例运行.这个进程用来分配大量的系统资源.这个进程对于系统的稳定和安全具有重要的意义,不能轻易的结束掉这个进程. 找到解决办法:(Windows2008中可以通过:服务器管理器->角色\web服务器\iis管理器 找到网站下的应用程序池,直接在程序池项的右键中修改) 解决CPU占用过多: 1.在IIS中对

压测过程中,CPU和内存占用率很高,案例简单分析

Q:  最近公司测试一个接口,数据库采用Mongo    并发策略:并发400个用户,每3秒加载5个用户,持续运行30分钟    数据量:8000条左右 压测结果发现:    TPS始终在5左右    而CPU高达99%,内存使用情况也高达1.7G    网卡流量145K 请问这种情况,是哪里的性能出现问题? A:你这个CPU和内存监控的得是web服务器 就是部署程序的机器.    1.尝试查看出现这类情况时候数据库process,看看是否是当时进程到达了所设置的进程数上限.如果是则调整数据库进

解决新装 Win 7 SP1 系统更新高CPU及内存占用率方法

最近重新安装了win7 sp1,系统更新始终无法工作,开始怀疑是驱动安装出现问题.但反复安装新旧驱动也解决不了问题,出现update服务cpu(Svchost.exe)占用居高不下的情况.网上也找了不少办法,什么重启服务,修复Windows更新服务等一系列不靠谱的方法,都是无济于事.几乎翻遍了整个互联网终于功夫不负有心人,找到了最终解决方法,就是需要提前安装一个补丁,但经过反复实验,事实证明需要安装两个补丁. 1.KB3102810 该补丁可以解决更新时CPU满载及大内存占用的情况 2.KB94