Linux下获取CPU利用率、温度、内存利用率
- 获取CPU利用率
double get_cpu_usage()
{
FILE* fd;
int tmp;
double a;
unsigned char buf[1024] = {0};
unsigned char msg[128] = {0};
unsigned int user1, nice1, sys1, idle1, iowait1, irq1, softirq1, total1;
unsigned int user2, nice2, sys2, idle2, iowait2, irq2, softirq2, total2;
retry:
fd = popen("cat /proc/stat | grep -w cpu | cut -d ' ' -f 3,4,5,6,7,8,9,10,11,12", "r");
if(fd == NULL)
{
Log("FILE:%s LINE:%d popen获取cpu利用率失败\n", __FILE__, __LINE__);
}
fgets(buf, sizeof(buf), fd);
char*p = strtok(buf, " ");
user1 = atoi(p);
p = strtok(NULL, " ");
nice1 = atoi(p);
p = strtok(NULL, " ");
sys1 = atoi(p);
p = strtok(NULL, " ");
idle1 = atoi(p);
p = strtok(NULL, " ");
iowait1 = atoi(p);
p = strtok(NULL, " ");
irq1 = atoi(p);
p = strtok(NULL, " ");
softirq1 = atoi(p);
sleep(1);
memset(buf, 0, sizeof(buf));
fd = popen("cat /proc/stat | grep -w cpu | cut -d ' ' -f 3,4,5,6,7,8,9,10,11,12", "r");
if(fd == NULL)
{
Log("FILE:%s LINE:%d popen获取cpu利用率失败\n", __FILE__, __LINE__);
// Log("查看cpu利用率失败\n");
}
fgets(buf, sizeof(buf), fd);
p = strtok(buf, " ");
user2 = atoi(p);
p = strtok(NULL, " ");
nice2 = atoi(p);
p = strtok(NULL, " ");
sys2 = atoi(p);
p = strtok(NULL, " ");
idle2 = atoi(p);
p = strtok(NULL, " ");
iowait2 = atoi(p);
p = strtok(NULL, " ");
irq2 = atoi(p);
p = strtok(NULL, " ");
softirq2 = atoi(p);
total1 = user1 + nice1 + sys1 + idle1 + iowait1 + irq1 + softirq1;
total2 = user2 + nice2 + sys2 + idle2 + iowait2 + irq2 + softirq2;
double usage = (double)(total2 - total1 - (idle2 - idle1)) / (double)(total2 - total1) * 100;
int aa = (int)(usage * 10000);
if(aa == 0) {
goto retry;
}
sprintf(msg, "cpu利用率 : %lf%%\n", usage);
Log(msg);
return usage;
}
- 获取CPU温度
double get_cpu_temp()
{
FILE* fd;
int tmp;
double a;
unsigned char buf[1024] = {0};
unsigned char msg[128] = {0};
fd = popen("cat /sys/class/hwmon/hwmon0/temp1_input", "r");
if(fd == NULL)
{
Log("FILE:%s LINE:%d popen获取cpu温度失败\n", __FILE__, __LINE__);
return -1;
}
fgets(buf, sizeof(buf), fd);
tmp = atoi((const char*)buf);
a = tmp / 1000.0;
sprintf(msg, "cpu温度 : %.2lf°C\n", a);
Log(msg);
return a;
}
- 获取内存利用率
double get_arm_usage()
{
FILE* fd;
int tmp;
double a;
unsigned char buf[1024] = {0};
unsigned char msg[128] = {0};
unsigned int total, use;
fd = popen("free | grep Mem | cut -d ' ' -f9,15", "r");
if(fd == NULL)
{
Log("FILE:%s LINE:%d popen获取内存利用率失败\n", __FILE__, __LINE__);
return -1;
}
fgets(buf, sizeof(buf), fd);
char*p = strtok(buf, " ");
total = atoi(p);
p = strtok(NULL, " ");
use = atoi(p);
// Log("total : %d use : %d\n", total, use);
double usage = use * 1.0 / total * 100;
sprintf(msg, "内存利用率 : %.4lf%%\n", usage);
Log(msg);
return usage;
}
仅供参考,部分信息存放位置需要根据自己的设备进行调整