c++ 代码获得linux cpu 当前总使用率

#include <stdio.h>
#include <signal.h>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
#include <list>
using namespace std;


std::string getValueBySystemCommand(std::string strCommand){
    //printf("-----%s------\n",strCommand.c_str());
    std::string strData = "";
    FILE * fp = NULL;
    char buffer[128];
    fp=popen(strCommand.c_str(),"r");
    if (fp) {
        while(fgets(buffer,sizeof(buffer),fp)){
            strData.append(buffer);
        }
        pclose(fp);
    }
    //printf("-----%s------ end\n",strCommand.c_str());
    return strData;
}


int runSystemCommand(std::string strCommand){
//    printf("-----%s------\n",strCommand.c_str());
    return system(strCommand.c_str());
}

string trim(string str)
{
    if (str.empty())
    {
        return str;
    }
    str.erase(0,str.find_first_not_of(" "));
    str.erase(str.find_last_not_of(" ") + 1);
    return str;
}

std::vector<std::string> split(std::string str, std::string pattern)
{
    string::size_type pos;
    vector<string> result;
    str += pattern;
    int size = str.size();
    
    for (int i = 0; i < size; i++) {
        pos = str.find(pattern, i);
        if (pos < size) {
            string s = str.substr(i, pos - i);
            result.push_back(s);
            i = pos + pattern.size() - 1;
        }
    }
    
    return result;
}

float getcpugap(){
    std::string strRes = getValueBySystemCommand("top -b -n 1 |grep Cpu | cut -d \",\" -f 1 | cut -d \":\" -f 2");
   
   strRes = trim(strRes);
   printf("--%s--  strRes.size : %lu \n", strRes.c_str(),strRes.length());
   std::vector<std::string> vecT = split(strRes," ");
   if (vecT.size() == 2){
       printf("%s\n", vecT.at(0).c_str());
       return atof(vecT.at(0).c_str());
   }
   return 0;
}

int main ()
{
   printf("start \n");
   signal(SIGCHLD, SIG_IGN);
   signal(SIGPIPE, SIG_IGN);
   signal(SIGILL, SIG_IGN);

   // std::string pstr = "%Cpu(s):  0.4 us,  0.9 sy,  0.0 ni, 98.7 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st";
   float cpugap =getcpugap();
   printf("%f\n", cpugap);
   return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值