利用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){