proc文件系统下的
/proc/stat,
/proc/meminfo,
/proc/<pid>/status,
/proc/<pid>/stat
总的cpu时间totalCpuTime = user + nice+ system + idle + iowait + irq + softirq + stealstolen + guest
进程的总Cpu时间processCpuTime = utime + stime + cutime + cstime
占用内存的计算方法:pmem = VmRSS / MemTotal * 100
计算CPU占用的方法:
取一次processCpuTime1和totalCpuTime1;
间隔一段时间;
再取一次processCpuTime2和totalCpuTime2;
pcpu = 100 * (processCpuTime2 – processCpuTime1)/(totalCpuTime2 - totalCpuTime1);
//-----------------mytop.cpp------------------------
#include<stdio.h>
#include<stdlib.h>#include<string.h>
#include <string>
#include<unistd.h>
#include<fcntl.h>
#include<ctype.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <asm/page.h>
#include <vector>
#include <assert.h>
#include<iostream>
using namespace std;
#define CK_TIME 1
struct FileAttribute
{
string path;
string name;
unsigned long long size;
time_t modify_timestamp;
bool is_dir;
};
int EnumFile(vector<FileAttribute> &file_array, string _dir)
{
DIR* dir=opendir(_dir.c_str()); //(".")
if(dir == NULL)
return 0;
struct dirent* entry;
while((entry=readdir(dir)))
{
if( strcmp( entry->d_name,".") ==0 || strcmp( entry->d_name,"..") ==0 )
continue;
FileAttribute fi;
fi.name = entry->d_name;
fi.is_dir = false;
string path;
if(_dir=="/"||(_dir.rfind("/")+1)>=_dir.length())
path=_dir+fi.name;
else
path = _dir+"/"+fi.name;
struct stat statbuf;
if (stat( path.c_str(),&statbuf ) < 0)
{
closedir(dir);
printf("stat error ! message: %s\n",strerror(errno));
return 0;
}
if (S_ISDIR(statbuf.st_mode))
{
fi.is_dir = true;
}
fi.size = statbuf.st_size;
fi.modify_timestamp =statbuf.st_mtime;
fi.path = path;
file_array.push_back(fi);
}
closedir(dir);
return file_array.size();
}
char * skip_token(const char *p)
{
while (isspace(*p)) p++;
while (*p && !isspace(*p)) p++;
return (char *)p;
}
int get_sys_mem(char *mem)
{
int tm,fm,bm,cm,ts,fs;
char buffer[4096+1];