利用Linux的/proc/stat获取指定进程的cpu占有率及内存

利用Linux的 /proc/stat计算进程的cpu占有率和内存

计算的是进程多个cpu的平均占有率,并不是每个cpu的,所以和top命令中的不一样

getinfo.cpp

  1 #include<stdlib.h>                                                                                                                                                                                     
  2 #include<string.h>
  3 #include<stdio.h>
  4 #include<unistd.h>
  5 #include<sys/time.h>
  6 
  7 #define VMRSS_LINE 17
  8 #define VMSIZE_LINE 13
  9 #define PROCESS_TIME 14
 10 
 11 typedef struct{
   
 12     unsigned long user;
 13     unsigned long nice;
 14     unsigned long system;
 15     unsigned long idle;
 16 }Total_Cpu_Occupy_t;
 17 
 18 typedef struct{
   
 19     unsigned int pid;
 20     unsigned long utime;
 21     unsigned long stime;
 22     unsigned long cutime;
 23     unsigned long cstime;
 24 }Proc_Cpu_Occupy_t;
 25 
 26 const char* get_items(const char*buffer,unsigned int item){
   
 27     const char*p=buffer;
 28     int len = strlen(buffer);
 29     int count=0;
 30     for (int i=0;i<len;i++){
   
 31         if(' '==*p){
   
 32             count++;
 33             if(count==item-1){
   
 34                 p++;
 35                 break;
 36             }
 37         }
 38         p++;
 39     }
 40     return p;
 41 }
 42 
 43 unsigned long get_cpu_total_occupy(){
   
 44     FILE *fd;
 45     char buff[1024]={
   0};
 46     Total_Cpu_Occupy_t t;
 47 
 48     fd=fopen("/proc/stat","r");
 49     if(nullptr==fd){
   
 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值