1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/extensions/api/system_cpu/cpu_info_provider.h"
10 #include "base/file_util.h"
11 #include "base/format_macros.h"
13 namespace extensions {
17 const char kProcStat[] = "/proc/stat";
21 bool CpuInfoProvider::QueryCpuTimePerProcessor(
22 std::vector<linked_ptr<api::system_cpu::ProcessorInfo> >* infos) {
26 if (!base::ReadFileToString(base::FilePath(kProcStat), &contents))
29 std::istringstream iss(contents);
32 // Skip the first line because it is just an aggregated number of
34 std::getline(iss, line);
36 while (std::getline(iss, line)) {
37 if (line.compare(0, 3, "cpu") != 0)
40 // The number of entries in /proc/stat may mismatch the size of infos
41 // because the number of online processors may change after the value has
42 // been decided in CpuInfoProvider::QueryInfo().
44 // TODO(jchuang): fix the fail case by using the number of configured
45 // processors instead of online processors.
46 if (i == infos->size()) {
47 LOG(ERROR) << "Got more entries in /proc/stat than online CPUs";
51 uint64 user = 0, nice = 0, sys = 0, idle = 0;
52 int vals = sscanf(line.c_str(),
53 "%*s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64,
54 &user, &nice, &sys, &idle);
57 infos->at(i)->usage.kernel = static_cast<double>(sys);
58 infos->at(i)->usage.user = static_cast<double>(user + nice);
59 infos->at(i)->usage.idle = static_cast<double>(idle);
60 infos->at(i)->usage.total = static_cast<double>(sys + user + nice + idle);
63 if (i < infos->size()) {
64 LOG(ERROR) << "Got fewer entries in /proc/stat than online CPUs";
71 } // namespace extensions