master
zcy 2022-03-27 20:33:34 -07:00
parent 450a27d200
commit 21eb616164
2 changed files with 92 additions and 0 deletions

View File

@ -1,6 +1,96 @@
#include "cpu_usage.h" #include "cpu_usage.h"
#include <iostream> #include <iostream>
#ifdef linux
using namespace std;
#define _LINE_LENGTH 300
bool GetCpuMem(float &cpu,size_t &mem, int pid,int tid = -1)
{
bool ret = false;
char cmdline[100];
sprintf(cmdline, "ps -o %%cpu,rss,%%mem,pid,tid -mp %d", pid);
FILE *file;
file = popen(cmdline, "r");
if (file == NULL)
{
printf("file == NULL\n");
return false;
}
char line[_LINE_LENGTH];
float l_cpuPrec=0;
int l_mem=0;
float l_memPrec=0;
int l_pid=0;
int l_tid=0;
if (fgets(line, _LINE_LENGTH, file) != NULL)
{
// printf("1st line:%s",line);
if (fgets(line, _LINE_LENGTH, file) != NULL)
{
// printf("2nd line:%s",line);
sscanf( line, "%f %d %f %d -", &l_cpuPrec, &l_mem, &l_memPrec, &l_pid );
cpu = l_cpuPrec;
mem = l_mem/1024;
if( tid == -1 )
ret = true;
else
{
while( fgets(line, _LINE_LENGTH, file) != NULL )
{
sscanf( line, "%f - - - %d", &l_cpuPrec, &l_tid );
// printf("other line:%s",line);
// cout<<l_cpuPrec<<'\t'<<l_tid<<endl;
if( l_tid == tid )
{
printf("cpuVal is tid:%d\n",tid);
cpu = l_cpuPrec;
ret = true;
break;
}
}
if( l_tid != tid )
printf("TID not exist\n");
}
}
else
printf("PID not exist\n");
}
else
printf("Command or Parameter wrong\n");
pclose(file);
return ret;
}
float CPUusage::GetCpuUsage()
{
float cpu;
size_t mem;
int pid;
int tid = -1;
if(GetCpuMem(cpu,mem,pid,tid))
return cpu;
else
return -1.0;
}
float CPUusage::GetMemoryUsage(){
float cpu;
size_t mem;
int pid;
int tid = -1;
if(GetCpuMem(cpu,mem,pid,tid))
return mem;
else
return -1.0;
}
#endif
#ifdef WINDOWS #ifdef WINDOWS

View File

@ -91,6 +91,8 @@ public:
printf("system cpu num is %d\n", sysconf( _SC_NPROCESSORS_CONF)); printf("system cpu num is %d\n", sysconf( _SC_NPROCESSORS_CONF));
printf("system enable cpu num is %d\n", sysconf(_SC_NPROCESSORS_ONLN)); printf("system enable cpu num is %d\n", sysconf(_SC_NPROCESSORS_ONLN));
} }
float GetCpuUsage();
float GetMemoryUsage();
CPUusage() { CPUusage() {