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