[cosmetics] update date in GPL header
[vuplus_xbmc] / xbmc / linux / LinuxResourceCounter.cpp
1 /*
2  *      Copyright (C) 2005-2013 Team XBMC
3  *      http://www.xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 #include "PlatformInclude.h"
22 #include "LinuxResourceCounter.h"
23 #include "utils/log.h"
24
25 #include <errno.h>
26
27 CLinuxResourceCounter::CLinuxResourceCounter()
28 {
29   Reset();
30 }
31
32 CLinuxResourceCounter::~CLinuxResourceCounter()
33 {
34 }
35
36 double CLinuxResourceCounter::GetCPUUsage()
37 {
38   struct timeval tmNow;
39   if (gettimeofday(&tmNow, NULL) == -1)
40     CLog::Log(LOGERROR, "error %d in gettimeofday", errno);
41   else
42   {
43     double dElapsed = ( ((double)tmNow.tv_sec + (double)tmNow.tv_usec / 1000000.0) -
44                  ((double)m_tmLastCheck.tv_sec + (double)m_tmLastCheck.tv_usec / 1000000.0) );
45
46     if (dElapsed >= 3.0)
47     {
48       struct rusage usage;
49       if (getrusage(RUSAGE_SELF, &usage) == -1)
50         CLog::Log(LOGERROR,"error %d in getrusage", errno);
51       else
52       {
53         double dUser = ( ((double)usage.ru_utime.tv_sec + (double)usage.ru_utime.tv_usec / 1000000.0) -
54                          ((double)m_usage.ru_utime.tv_sec + (double)m_usage.ru_utime.tv_usec / 1000000.0) );
55         double dSys  = ( ((double)usage.ru_stime.tv_sec + (double)usage.ru_stime.tv_usec / 1000000.0) -
56                   ((double)m_usage.ru_stime.tv_sec + (double)m_usage.ru_stime.tv_usec / 1000000.0) );
57
58         m_tmLastCheck = tmNow;
59         m_usage = usage;
60         m_dLastUsage = ((dUser+dSys) / dElapsed) * 100.0;
61         return m_dLastUsage;
62       }
63     }
64   }
65
66   return m_dLastUsage;
67 }
68
69 void CLinuxResourceCounter::Reset()
70 {
71   if (gettimeofday(&m_tmLastCheck, NULL) == -1)
72     CLog::Log(LOGERROR, "error %d in gettimeofday", errno);
73
74   if (getrusage(RUSAGE_SELF, &m_usage) == -1)
75     CLog::Log(LOGERROR, "error %d in getrusage", errno);
76
77   m_dLastUsage = 0.0;
78 }
79
80
81
82
83