计算Linux系统和进程和线程的CPU及内存使用率(c++源码)

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];
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值