
1. 进入了一个死循环无法跳出来;
2. 也许是一直在等待一个信号,如从dbus上读取一个你需要的信息;
3. 有可能是你的程序在对一个非常大的内容进行分析和处理;
4. 有可能是你的程序要处理的问题比较多,所以在一个个慢慢的执行。
大部分是由上面四种情况引起的,在这四种情况中,第一种情况坚决要避免,因为不如此,那么你的CPU资源将会被吃光。第二种情况,我的想法是,你要修改一下,看看有没有什么更快,更高效的方法来获取到需要的信号,或者是不去获取信号,而是改用其他方式来处理。第三和第四两种情况,就要根据你的实际需要来定了。如果是必须这样做,那么也只能够耐心的等待了。但是可以考虑优化代码,优化算法的方式来提高效率。
Linux系统下有个很好的调试工具gdb。如果不知道自己的程序出现了什么问题,可以利用gdb工具逐步执行,去查找错误所在。
我附上我的代码给你参考。
CPU占用 需要查看/proc/stat 的信息
磁盘需要 使用statfs这个函数来确认文件所包含的信息。
我附上我的代码给你参考。
我的代码支持CPU使用率(占用率),内存占用率,及磁盘占用率。
#include <stdio.h>#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/vfs.h>
#include <error.h>
#define Gsize (1024.00*1024.00*1024.00)
#define Msize (1024.00*1024.00)
#ifndef EXT2_SUPER_MAGIC
#define EXT2_SUPER_MAGIC 0xef53
#endif
double time_so_far()
float get_cpu_rate()
float get_memory_rate()
float get_disk_rate()
int main(int argc,char *argv[])
{
get_cpu_rate()
get_memory_rate()
get_disk_rate()
return 0
}
double time_so_far(){
struct timeval tp
if(gettimeofday(&tp,(struct timezone *)NULL) == -1)
perror("gettimeofday")
return ((double)(tp.tv_sec))+(((double)tp.tv_usec)*0.000001)
}
float get_cpu_rate(){
FILE *f1
double ti,tf
char c[10],d[10]
int t,i1,i2,i3,i4,i5,i6
ti=time_so_far()
f1=fopen("/proc/stat","r")
fscanf(f1,"%s\t%d\t%d\t%d\n",c,&i1,&i2,&i3)
fclose(f1)
printf("%s\t%d\t%d\t%d\n",c,i1,i2,i3)
usleep(1000000)
tf=time_so_far()
f1=fopen("/proc/stat","r")
fscanf(f1,"%s\t%d\t%d\t%d\n",c,&i4,&i5,&i6)
fclose(f1)
printf("%s\t%d\t%d\t%d\n",c,i4,i5,i6)
t=(i4+i5+i6)-(i1+i2+i3)
printf("%d\n",t)
printf("cpu usage: %.2f%%\n",( t/((tf-ti)*100) )*100 )
}
float get_memory_rate(){
FILE *f1
int itemp1,itemp2
char c[10],d[10]
f1=fopen("/proc/meminfo","r")
fscanf(f1,"%s\t%d\t%s",c,&itemp1,d)
printf("memory total is %d Kb\n",itemp1)
printf("memory total is %.2f Mb\n",itemp1/1024.0)
fscanf(f1,"%s\t%d\t%s",c,&itemp2,d)
printf("memory free is %d Kb\n",itemp2)
printf("memory free is %.2f Mb\n",itemp2/1024.0)
fclose(f1)
printf("men usage : %.2f%%\n",((itemp1-itemp2)*100.0)/itemp1)
}
float get_disk_rate(){
struct statfs *fs
long long blocks,bfree
if(statfs("/",fs) != 0)
{
perror("stafts")
printf("exit\n")
exit(1)
}
blocks=fs->f_blocks
bfree=fs->f_bfree
//if(fs.f_type == EXT2_SUPER_MAGIC)
//{
printf("Disk size of / is %.2f G\n",blocks*fs->f_bsize/Gsize)
printf("Free Disk size of / is %.2f G\n",bfree*fs->f_bsize/Gsize)
printf("Disk usage of / is %.2f%% \n",bfree*100.0/blocks)
//}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)