OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #include "chrome/browser/extensions/api/system_cpu/cpu_info_provider.h" | |
6 | |
7 #include <cstdio> | |
8 #include <sstream> | |
9 | |
10 #include "base/files/file_util.h" | |
11 #include "base/format_macros.h" | |
12 | |
13 namespace extensions { | |
14 | |
15 namespace { | |
16 | |
17 const char kProcStat[] = "/proc/stat"; | |
18 | |
19 } // namespace | |
20 | |
21 bool CpuInfoProvider::QueryCpuTimePerProcessor( | |
22 std::vector<linked_ptr<api::system_cpu::ProcessorInfo> >* infos) { | |
23 DCHECK(infos); | |
24 | |
25 // WARNING: this method may return incomplete data because some processors may | |
26 // be brought offline at runtime. /proc/stat does not report statistics of | |
27 // offline processors. CPU usages of offline processors will be filled with | |
28 // zeros. | |
29 // | |
30 // An example of output of /proc/stat when processor 0 and 3 are online, but | |
31 // processor 1 and 2 are offline: | |
32 // | |
33 // cpu 145292 20018 83444 1485410 995 44 3578 0 0 0 | |
34 // cpu0 138060 19947 78350 1479514 570 44 3576 0 0 0 | |
35 // cpu3 2033 32 1075 1400 52 0 1 0 0 0 | |
36 std::string contents; | |
37 if (!base::ReadFileToString(base::FilePath(kProcStat), &contents)) | |
38 return false; | |
39 | |
40 std::istringstream iss(contents); | |
41 std::string line; | |
42 | |
43 // Skip the first line because it is just an aggregated number of | |
44 // all cpuN lines. | |
45 std::getline(iss, line); | |
46 while (std::getline(iss, line)) { | |
47 if (line.compare(0, 3, "cpu") != 0) | |
48 continue; | |
49 | |
50 uint64 user = 0, nice = 0, sys = 0, idle = 0; | |
51 uint32 pindex = 0; | |
52 int vals = sscanf(line.c_str(), | |
53 "cpu%" PRIu32 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, | |
54 &pindex, &user, &nice, &sys, &idle); | |
55 if (vals != 5 || pindex >= infos->size()) { | |
56 NOTREACHED(); | |
57 return false; | |
58 } | |
59 | |
60 infos->at(pindex)->usage.kernel = static_cast<double>(sys); | |
61 infos->at(pindex)->usage.user = static_cast<double>(user + nice); | |
62 infos->at(pindex)->usage.idle = static_cast<double>(idle); | |
63 infos->at(pindex)->usage.total = static_cast<double>(sys + user + | |
64 nice + idle); | |
65 } | |
66 | |
67 return true; | |
68 } | |
69 | |
70 } // namespace extensions | |
OLD | NEW |