改进后的计算CPU的使用率实现

网上查阅了一些资料,看到最多的一个文档,内部是用sleep(1)这样的实现,而sleep这个函数是阻塞睡眠,相当于让cpu在这一秒钟内停运,对整个系统的影响还是非常大的。更严重的是影响通信,甚至错误。

其实修改不是很多,可以使用alarm调用等等。


typedef struct cpu_info
{
	char name[20];      	
	unsigned int user; 		
	unsigned int nice;		
	unsigned int system;	
	unsigned int idle; 
}CPU_USE;
void get_cpu_node_info (CPU_USE *cpust);
int calculate_cpu_use (CPU_USE *o, CPU_USE *n);
int get_cpustat_of_use( void );


/*
 * @brief	: For a time the state of the CPU
 * @param[out]	: struct CPU_USE
 * @return 	: 
 */
void get_cpu_node_info (CPU_USE *cpust)
{    
	FILE *fd;           
	int n;               
	char buff[256];  
	CPU_USE *cpu_occupy;    
	cpu_occupy=cpust; 

	fd = fopen ("/proc/stat", "r");    
	fgets (buff, sizeof(buff), fd);      


	sscanf (buff, "%s %u %u %u %u", cpu_occupy->name, &cpu_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle);      
	fclose(fd);      

}

/*
 * @brief	: Occupation calculation rate of CPU
 * @return 	: rate of CPU
 */
int calculate_cpu_use (CPU_USE *o, CPU_USE *n)
{
	unsigned long od, nd;      
	unsigned long id, sd, id_t;   
	int cpu_use = 0;         
	od = (unsigned long) (o->user + o->nice + o->system +o->idle);
	nd = (unsigned long) (n->user + n->nice + n->system +n->idle);
	id_t = n->idle - o->idle;

	cpu_use = 100 * (nd - od - id_t)/(nd-od);
	return cpu_use;
}  

/*
 * @brief	: to obtain the CPU utilization rate
 * @return 	: rate
 */

CPU_USE cpu_stat1;   
int get_cpustat_of_use( void )
{
	CPU_USE cpu_stat2;    
	int cpu;      

	get_cpu_node_info((CPU_USE *)&cpu_stat2);
	cpu = calculate_cpu_use ((CPU_USE *)&cpu_stat1, (CPU_USE *)&cpu_stat2);   
	cpu_stat1 = cpu_stat2;

	return cpu;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值