C++工程,获取Cpu、内存使用率

文章目录

  • 1,使用
  • 2,函数实现

1,使用

int main() {
 	while(pipeline_run_flag) {
        system("top -s -b -n 1 |grep -E \"Cpu|KiB Mem |KiB Swap\" > log/sys_state.txt");
        
        write_system_state_to_log("log/sys_state.txt");
        usleep(1000*1000);
    }
}

2,函数实现

// write system state to log
void write_system_state_to_log(std::string filename) 
{ 
    std::ifstream fp;
    std::string rtline, szLine;
    std::string total_t, free_t, used_t, buffer_t; 
	std::string::size_type pos1, pos2;
    
    fp.open(filename);
    if (!fp.is_open()) {
		LOG(ERROR) << "Error: can not find file: " << filename;
    }
    else {
        LOG(WARNING) << filename << " open successful! ";
    }
    
    // CUP%
	getline(fp, rtline);
    szLine = rtline.c_str();
    LOG(WARNING) << szLine;

    // MEM
	getline(fp, rtline);
    szLine = rtline.c_str();
//     LOG(WARNING) << szLine;
	
    pos1 = szLine.find(':')+1;
    szLine = szLine.substr(pos1);
	pos2 = szLine.find('t');
	total_t = szLine.substr(0, pos2).c_str();
    
    pos1 = szLine.find(',')+1;
    szLine = szLine.substr(pos1);
	pos2 = szLine.find('f');
	free_t = szLine.substr(0, pos2).c_str();

    pos1 = szLine.find(',')+1;
    szLine = szLine.substr(pos1);
	pos2 = szLine.find('u');
	used_t = szLine.substr(0, pos2).c_str();

    pos1 = szLine.find(',')+1;
    szLine = szLine.substr(pos1);
	pos2 = szLine.find('b');
	buffer_t = szLine.substr(0, pos2).c_str();

    float total = a2i(total_t);
    float free = a2i(free_t)/total * 100;
    float used = a2i(used_t)/total * 100;
    float buffer = a2i(buffer_t)/total * 100;
    LOG(WARNING) << "KiB Mem : " 
        << std::setiosflags(std::ios::fixed) << std::setprecision(0) 
        << total << " total, " 
        << std::setiosflags(std::ios::fixed) << std::setprecision(2) 
        << free << "\% free, " 
        << std::setiosflags(std::ios::fixed) << std::setprecision(2) 
        << used << "\% used, " 
        << std::setiosflags(std::ios::fixed) << std::setprecision(2) 
        << buffer << "\% buff/cache";
	
    // SWAP
    getline(fp, rtline);
    szLine = rtline.c_str();
    LOG(WARNING) << szLine;
	
    fp.close();
}


int a2i(std::string str) {
    int num = 0;
    int i = 0;
    while(i <= str.size()) {
        if(str[i] >= '0' && str[i] <= '9') {
            num = num * 10 + str[i] - '0';
//             std::cout << "str[" << i << "]: " << str[i] << std::endl;
        } 
        i++;
    }
    return num;
}

你可能感兴趣的:(C++工程)