2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
21 #include <Commons/Exception.h>
25 const unsigned int GET_STATS_TIMEOUT = 1; // in seconds
26 const char* STAT_FILE = "/proc/stat";
27 const char* CPU_PATTERN_PREFIX = "^cpu";
28 const char* CPU_PATTERN_POSTFIX = "\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)";
31 namespace WrtDeviceApis {
34 Unit::Unit(std::size_t index) : m_index(index)
36 std::ostringstream oss(CPU_PATTERN_PREFIX);
40 oss << CPU_PATTERN_POSTFIX;
41 m_utilizationPattern = oss.str();
44 unsigned int Unit::getUtilizationPercent() const
46 UtilizationStats usage0 = getUtilization();
47 sleep(GET_STATS_TIMEOUT);
48 UtilizationStats usage1 = getUtilization();
50 unsigned sum0 = usage0.m_user + usage0.m_nice + usage0.m_system +
52 unsigned sum1 = usage1.m_user + usage1.m_nice + usage1.m_system +
58 usage0.m_idle) / (double) (sum1 - sum0)) * 100);
63 Unit::UtilizationStats Unit::getUtilization() const
65 std::ifstream file(STAT_FILE);
67 ThrowMsg(Commons::UnsupportedException,
68 "Could not open statistics file.");
71 UtilizationStats result;
72 memset(&result, 0, sizeof(UtilizationStats));
75 while (!file.eof() && !!std::getline(file, line)) {
76 if (pcrecpp::RE(m_utilizationPattern.c_str()).FullMatch(
90 ThrowMsg(Commons::UnsupportedException, "Total memory data not found.");