1 // Copyright (c) 2013 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 "base/process/process_metrics.h"
6 
7 #include <stddef.h>
8 #include <stdint.h>
9 #include <sys/param.h>
10 #include <sys/sysctl.h>
11 
12 #include "base/memory/ptr_util.h"
13 #include "base/process/process_metrics_iocounters.h"
14 #include "base/stl_util.h"
15 
16 namespace base {
17 
18 // static
CreateProcessMetrics(ProcessHandle process)19 std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
20     ProcessHandle process) {
21   return WrapUnique(new ProcessMetrics(process));
22 }
23 
GetIOCounters(IoCounters * io_counters) const24 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
25   return false;
26 }
27 
GetProcessCPU(pid_t pid)28 static int GetProcessCPU(pid_t pid) {
29   struct kinfo_proc info;
30   size_t length;
31   int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid,
32                 sizeof(struct kinfo_proc), 0 };
33 
34   if (sysctl(mib, base::size(mib), NULL, &length, NULL, 0) < 0)
35     return -1;
36 
37   mib[5] = (length / sizeof(struct kinfo_proc));
38 
39   if (sysctl(mib, base::size(mib), &info, &length, NULL, 0) < 0)
40     return 0;
41 
42   return info.p_pctcpu;
43 }
44 
GetPlatformIndependentCPUUsage()45 double ProcessMetrics::GetPlatformIndependentCPUUsage() {
46   TimeTicks time = TimeTicks::Now();
47 
48   if (last_cpu_time_.is_zero()) {
49     // First call, just set the last values.
50     last_cpu_time_ = time;
51     return 0;
52   }
53 
54   int cpu = GetProcessCPU(process_);
55 
56   last_cpu_time_ = time;
57   double percentage = static_cast<double>((cpu * 100.0) / FSCALE);
58 
59   return percentage;
60 }
61 
GetCumulativeCPUUsage()62 TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
63   NOTREACHED();
64   return TimeDelta();
65 }
66 
ProcessMetrics(ProcessHandle process)67 ProcessMetrics::ProcessMetrics(ProcessHandle process)
68     : process_(process),
69       last_cpu_(0) {}
70 
GetSystemCommitCharge()71 size_t GetSystemCommitCharge() {
72   int mib[] = { CTL_VM, VM_METER };
73   int pagesize;
74   struct vmtotal vmtotal;
75   unsigned long mem_total, mem_free, mem_inactive;
76   size_t len = sizeof(vmtotal);
77 
78   if (sysctl(mib, base::size(mib), &vmtotal, &len, NULL, 0) < 0)
79     return 0;
80 
81   mem_total = vmtotal.t_vm;
82   mem_free = vmtotal.t_free;
83   mem_inactive = vmtotal.t_vm - vmtotal.t_avm;
84 
85   pagesize = getpagesize();
86 
87   return mem_total - (mem_free*pagesize) - (mem_inactive*pagesize);
88 }
89 
90 }  // namespace base
91