1 #ifndef _CPU_USAGE_LINUX_H_
2 #define _CPU_USAGE_LINUX_H_
3 
4 #include <sys/time.h>
5 #include <sys/resource.h>
6 
7 #include <glibtop.h>
8 #include <glibtop/cpu.h>
9 
10 class ESCpuUsage
11 {
12 	Base::CTimer	m_Timer;
13 	fp8				m_LastCPUCheckTime;
14 
15 	fp8  m_LastSystemTime;
16 	fp8  m_LastESTime;
17 
18 	glibtop *glibtopdata;
19 	glibtop_cpu m_lastProcessorInfo, m_currentProcessorInfo;
20 
21 	int numProcessors;
22 
23 public:
ESCpuUsage()24 	ESCpuUsage(): m_LastCPUCheckTime(0)
25 	{
26 
27 	  glibtopdata = glibtop_init();
28 
29 	  m_Timer.Reset();
30 	  m_LastCPUCheckTime = m_Timer.Time();
31 
32 	  struct rusage r_usage;
33 	  if (!getrusage(RUSAGE_SELF, &r_usage)) {
34 
35 	    m_LastESTime = (fp8)r_usage.ru_utime.tv_sec + (fp8)r_usage.ru_utime.tv_usec * 1e-6;
36 
37 	    m_LastESTime += (fp8)r_usage.ru_stime.tv_sec + (fp8)r_usage.ru_stime.tv_usec * 1e-6;
38 
39 	  }
40 
41 	  numProcessors = glibtopdata->ncpu + 1;
42 	  glibtop_get_cpu (&m_lastProcessorInfo);
43 	}
44 
~ESCpuUsage()45 	virtual ~ESCpuUsage()
46 	{
47 	}
48 
GetCpuUsage(int & _total,int & _es)49 	bool GetCpuUsage(int &_total, int &_es)
50 	{
51 	  struct rusage r_usage;
52 
53 		fp8 newtime = m_Timer.Time();
54 
55 		fp8 period =  newtime - m_LastCPUCheckTime;
56 		if (period > 0.)
57 		{
58 		  if (!getrusage(RUSAGE_SELF, &r_usage))
59 			{
60 
61 			  fp8 utime = (fp8)r_usage.ru_utime.tv_sec + (fp8)r_usage.ru_utime.tv_usec * 1e-6;
62 
63 			  utime += (fp8)r_usage.ru_stime.tv_sec + (fp8)r_usage.ru_stime.tv_usec * 1e-6;
64 
65 			  _es = int ( ( utime - m_LastESTime ) * 100. / period );
66 
67 			  m_LastESTime = utime;
68 			}
69 
70 		  float accInUse = 0.0f, accTotal = 0.0f;
71 
72 		  glibtop_get_cpu (&m_currentProcessorInfo);
73 
74 		  for(unsigned i = 0U; i < numProcessors; ++i)
75 		    {
76 		      float inUse, total;
77 
78 		      inUse = (
79 			       (m_currentProcessorInfo.xcpu_user[i]   - m_lastProcessorInfo.xcpu_user[i])
80 			       + (m_currentProcessorInfo.xcpu_sys[i] - m_lastProcessorInfo.xcpu_sys[i])
81 			       + (m_currentProcessorInfo.xcpu_nice[i] - m_lastProcessorInfo.xcpu_nice[i])
82 			       );
83 
84 		      total = inUse + (m_currentProcessorInfo.xcpu_idle[i] - m_lastProcessorInfo.xcpu_idle[i]);
85 
86 		      accInUse += inUse;
87 		      accTotal += total;
88 		    }
89 
90 		  _total = (fp8)accInUse * 100. / (fp8)accTotal;
91 
92 		  _es /= numProcessors;
93 
94 		  memcpy(&m_lastProcessorInfo, &m_currentProcessorInfo, sizeof( glibtop_cpu ) );
95 
96 		}
97 		else
98 		  {
99 		    _es = 0;
100 		    _total = 0;
101 		  }
102 
103 		_es = ::Base::Math::Clamped(_es, 0, 100);
104 		_total = ::Base::Math::Clamped(_total, 0, 100);
105 
106 		m_LastCPUCheckTime = newtime;
107 
108 		return true;
109 	}
110 
111 };
112 
113 
114 #endif
115