//通过命令获取 top -n 1 | grep Cpu
double CPUInfo::GetCPU()
{
TODO://获取总的cpu使用率
double cpu = 0.0;
cpu = getcpuBycmd(); //通过命令获取cpu使用率
return cpu;
}
double CPUInfo::getcpuBycmd()
{
double us_cpu = 0.0;
char str_us_cpu[20] = "none";
char str_sys_cpu[20] = "none";
getCpuInfo(str_us_cpu, str_sys_cpu); //判断一下返回值
//printf("\n%s %s\n", str1, str2);
std::cout << "test_getcpuBycmd: " << "us_cpu = " << str_us_cpu << " sys_cpu = " << str_sys_cpu << std::endl;
sscanf(str_us_cpu, "%lf", &us_cpu);
return us_cpu;
}
//获取cpu的用户使用率和系统使用率
int CPUInfo::getCpuInfo(char *cpuUser, char *cpuSystem)
{
char buffer[2000] = "";
int flag;
if ((NULL == cpuUser) || (NULL == cpuSystem))
{
printf("\ngetCpuInfo param null!\n");
return 0;
}
if (1 == (flag = executeCmd(CPU_ORDER, buffer, READ)))//执行top -n 1 | grep Cpu命令
{
sscanf(buffer, "%*s%s%*s%s%*s", cpuUser, cpuSystem);//读取cpu用户使用率和系统使用率
}
return 1;
}
linux获取cpu使用
最新推荐文章于 2024-08-05 08:45:11 发布