linux,cpu利用率

#include <stdio.h>
#include<stdlib.h>
#define uint unsigned int

#define N 20


typedef struct{
	char cpu[10];
	uint user_t;
	uint nice_t;
	uint system_t;
	uint idel_t;
	uint iowait_t;
	uint irq_t;
	uint sirq_t;
}CPU;
struct sysinfo {
	long uptime;             /* Seconds since boot */
	unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
	unsigned long totalram;  /* Total usable main memory size */
	unsigned long freeram;   /* Available memory size */
	unsigned long sharedram; /* Amount of shared memory */
	unsigned long bufferram; /* Memory used by buffers */
	unsigned long totalswap; /* Total swap space size */
	unsigned long freeswap;  /* swap space still available */
	unsigned short procs;    /* Number of current processes */
	char _f[22];             /* Pads structure to 64 bytes */
};

int get_cpu(CPU op[] );//获取cpu _i的在stat值
float cpul(CPU op1[],CPU op2[]);//计算利用率
int getmen(struct sysinfo *info);//获取内存值

int main(int argc,const char *argv[])
{

	CPU op1[N],op2[N];
	struct sysinfo info;
	int i=0,j=0;
	//float cpu;
	while(1){
		get_cpu(op1);
		sleep(1);
		get_cpu(op2);
		system("clear");
		cpul(op1,op2);

		getmen(&info);
		printf("tatal men: %ld\t free mem: %ld\ntotal swap: %ld\t free swap:%ld\n\n",info.totalram/1024,info.freeram/1024,info.totalswap/1024,info.freeswap/1024);

	}

	return 0;
}
int get_cpu(CPU op1[]){//向函数中传入CUP数组
	FILE *fp;
	char buf[100];
	int i=0;
	CPU op;
	//proc/stat
	fp = fopen("/proc/stat","r");//只是打开文件,得到地址
	while(1){

		fgets(buf,100,fp);//获取一行
		
		sscanf(buf,"%s  %d %d %d %d %d %d %d",
				op.cpu,&op.user_t,&op.nice_t,&op.system_t,
				&op.idel_t,&op.iowait_t,&op.irq_t,&op.sirq_t);
		op1[i] = op;


		i++;	
		if(op.cpu[0] != 'c' || op.cpu[1] != 'p' )
		{
			fclose(fp);
			break;
		}
	}

	return 0;

}

float cpul(CPU op1[],CPU op2[]){
	float t1,t2,u1,u2;
	float cpul;
	int i=0;
	while(1){

		t1 = op1[i].user_t + op1[i].nice_t + op1[i].system_t + 
			op1[i].idel_t + op1[i].iowait_t + op1[i].irq_t + op1[i].sirq_t;
		t2 = op2[i].user_t + op2[i].nice_t + op2[i].system_t + 
			op2[i].idel_t + op2[i].iowait_t + op2[i].irq_t + op2[i].sirq_t;
		u1= op1[i].user_t + op1[i].nice_t + op1[i].system_t;
		u2 = op2[i].user_t + op2[i].nice_t + op2[i].system_t;
		printf("%s:",op1[i].cpu);
		if(t2 - t1 == 0)
			cpul = 0;
		else
			cpul = (u2 - u1) / (t2 - t1);
		printf("%f\n",cpul);	
		i++;	
		if(op1[i].cpu[0] != 'c' || op1[i].cpu[1] != 'p' )
			break;
	}

}
int getmen(struct sysinfo *info){
	sysinfo(info);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值