Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / base / process / process_metrics.h
blob8b4ec86693ac9aaceae50b1ce77d8549eaf32565
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.
5 // This file contains routines for gathering resource statistics for processes
6 // running on the system.
8 #ifndef BASE_PROCESS_PROCESS_METRICS_H_
9 #define BASE_PROCESS_PROCESS_METRICS_H_
11 #include <string>
13 #include "base/base_export.h"
14 #include "base/basictypes.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/process/process_handle.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
20 #if defined(OS_MACOSX)
21 #include <mach/mach.h>
22 #endif
24 namespace base {
26 #if defined(OS_WIN)
27 struct IoCounters : public IO_COUNTERS {
29 #elif defined(OS_POSIX)
30 struct IoCounters {
31 uint64_t ReadOperationCount;
32 uint64_t WriteOperationCount;
33 uint64_t OtherOperationCount;
34 uint64_t ReadTransferCount;
35 uint64_t WriteTransferCount;
36 uint64_t OtherTransferCount;
38 #endif
40 // Working Set (resident) memory usage broken down by
42 // On Windows:
43 // priv (private): These pages (kbytes) cannot be shared with any other process.
44 // shareable: These pages (kbytes) can be shared with other processes under
45 // the right circumstances.
46 // shared : These pages (kbytes) are currently shared with at least one
47 // other process.
49 // On Linux:
50 // priv: Pages mapped only by this process.
51 // shared: PSS or 0 if the kernel doesn't support this.
52 // shareable: 0
54 // On ChromeOS:
55 // priv: Pages mapped only by this process.
56 // shared: PSS or 0 if the kernel doesn't support this.
57 // shareable: 0
58 // swapped Pages swapped out to zram.
60 // On OS X: TODO(thakis): Revise.
61 // priv: Memory.
62 // shared: 0
63 // shareable: 0
65 struct WorkingSetKBytes {
66 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
67 size_t priv;
68 size_t shareable;
69 size_t shared;
70 #if defined(OS_CHROMEOS)
71 size_t swapped;
72 #endif
75 // Committed (resident + paged) memory usage broken down by
76 // private: These pages cannot be shared with any other process.
77 // mapped: These pages are mapped into the view of a section (backed by
78 // pagefile.sys)
79 // image: These pages are mapped into the view of an image section (backed by
80 // file system)
81 struct CommittedKBytes {
82 CommittedKBytes() : priv(0), mapped(0), image(0) {}
83 size_t priv;
84 size_t mapped;
85 size_t image;
88 // Convert a POSIX timeval to microseconds.
89 BASE_EXPORT int64 TimeValToMicroseconds(const struct timeval& tv);
91 // Provides performance metrics for a specified process (CPU usage, memory and
92 // IO counters). To use it, invoke CreateProcessMetrics() to get an instance
93 // for a specific process, then access the information with the different get
94 // methods.
95 class BASE_EXPORT ProcessMetrics {
96 public:
97 ~ProcessMetrics();
99 // Creates a ProcessMetrics for the specified process.
100 // The caller owns the returned object.
101 #if !defined(OS_MACOSX) || defined(OS_IOS)
102 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
103 #else
104 class PortProvider {
105 public:
106 virtual ~PortProvider() {}
108 // Should return the mach task for |process| if possible, or else
109 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
110 // metrics on OS X (except for the current process, which always gets
111 // metrics).
112 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
115 // The port provider needs to outlive the ProcessMetrics object returned by
116 // this function. If NULL is passed as provider, the returned object
117 // only returns valid metrics if |process| is the current process.
118 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
119 PortProvider* port_provider);
120 #endif // !defined(OS_MACOSX) || defined(OS_IOS)
122 // Returns the current space allocated for the pagefile, in bytes (these pages
123 // may or may not be in memory). On Linux, this returns the total virtual
124 // memory size.
125 size_t GetPagefileUsage() const;
126 // Returns the peak space allocated for the pagefile, in bytes.
127 size_t GetPeakPagefileUsage() const;
128 // Returns the current working set size, in bytes. On Linux, this returns
129 // the resident set size.
130 size_t GetWorkingSetSize() const;
131 // Returns the peak working set size, in bytes.
132 size_t GetPeakWorkingSetSize() const;
133 // Returns private and sharedusage, in bytes. Private bytes is the amount of
134 // memory currently allocated to a process that cannot be shared. Returns
135 // false on platform specific error conditions. Note: |private_bytes|
136 // returns 0 on unsupported OSes: prior to XP SP2.
137 bool GetMemoryBytes(size_t* private_bytes,
138 size_t* shared_bytes);
139 // Fills a CommittedKBytes with both resident and paged
140 // memory usage as per definition of CommittedBytes.
141 void GetCommittedKBytes(CommittedKBytes* usage) const;
142 // Fills a WorkingSetKBytes containing resident private and shared memory
143 // usage in bytes, as per definition of WorkingSetBytes. Note that this
144 // function is somewhat expensive on Windows (a few ms per process).
145 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
147 #if defined(OS_MACOSX)
148 // Fills both CommitedKBytes and WorkingSetKBytes in a single operation. This
149 // is more efficient on Mac OS X, as the two can be retrieved with a single
150 // system call.
151 bool GetCommittedAndWorkingSetKBytes(CommittedKBytes* usage,
152 WorkingSetKBytes* ws_usage) const;
153 #endif
155 // Returns the CPU usage in percent since the last time this method or
156 // GetPlatformIndependentCPUUsage() was called. The first time this method
157 // is called it returns 0 and will return the actual CPU info on subsequent
158 // calls. On Windows, the CPU usage value is for all CPUs. So if you have
159 // 2 CPUs and your process is using all the cycles of 1 CPU and not the other
160 // CPU, this method returns 50.
161 double GetCPUUsage();
163 // Returns the number of average idle cpu wakeups per second since the last
164 // call.
165 int GetIdleWakeupsPerSecond();
167 // Same as GetCPUUsage(), but will return consistent values on all platforms
168 // (cancelling the Windows exception mentioned above) by returning a value in
169 // the range of 0 to (100 * numCPUCores) everywhere.
170 double GetPlatformIndependentCPUUsage();
172 // Retrieves accounting information for all I/O operations performed by the
173 // process.
174 // If IO information is retrieved successfully, the function returns true
175 // and fills in the IO_COUNTERS passed in. The function returns false
176 // otherwise.
177 bool GetIOCounters(IoCounters* io_counters) const;
179 private:
180 #if !defined(OS_MACOSX) || defined(OS_IOS)
181 explicit ProcessMetrics(ProcessHandle process);
182 #else
183 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
184 #endif // !defined(OS_MACOSX) || defined(OS_IOS)
186 #if defined(OS_LINUX) || defined(OS_ANDROID)
187 bool GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage) const;
188 #endif
190 #if defined(OS_CHROMEOS)
191 bool GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage) const;
192 #endif
194 #if defined(OS_MACOSX) || defined(OS_LINUX)
195 int CalculateIdleWakeupsPerSecond(uint64 absolute_idle_wakeups);
196 #endif
198 ProcessHandle process_;
200 int processor_count_;
202 // Used to store the previous times and CPU usage counts so we can
203 // compute the CPU usage between calls.
204 TimeTicks last_cpu_time_;
205 int64 last_system_time_;
207 #if defined(OS_MACOSX) || defined(OS_LINUX)
208 // Same thing for idle wakeups.
209 TimeTicks last_idle_wakeups_time_;
210 uint64 last_absolute_idle_wakeups_;
211 #endif
213 #if !defined(OS_IOS)
214 #if defined(OS_MACOSX)
215 // Queries the port provider if it's set.
216 mach_port_t TaskForPid(ProcessHandle process) const;
218 PortProvider* port_provider_;
219 #elif defined(OS_POSIX)
220 // Jiffie count at the last_cpu_time_ we updated.
221 int last_cpu_;
222 #endif // defined(OS_POSIX)
223 #endif // !defined(OS_IOS)
225 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
228 // Returns the memory committed by the system in KBytes.
229 // Returns 0 if it can't compute the commit charge.
230 BASE_EXPORT size_t GetSystemCommitCharge();
232 // Returns the number of bytes in a memory page.
233 BASE_EXPORT size_t GetPageSize();
235 #if defined(OS_POSIX)
236 // Returns the maximum number of file descriptors that can be open by a process
237 // at once. If the number is unavailable, a conservative best guess is returned.
238 BASE_EXPORT size_t GetMaxFds();
240 // Sets the file descriptor soft limit to |max_descriptors| or the OS hard
241 // limit, whichever is lower.
242 BASE_EXPORT void SetFdLimit(unsigned int max_descriptors);
243 #endif // defined(OS_POSIX)
245 #if defined(OS_LINUX) || defined(OS_ANDROID)
246 // Parse the data found in /proc/<pid>/stat and return the sum of the
247 // CPU-related ticks. Returns -1 on parse error.
248 // Exposed for testing.
249 BASE_EXPORT int ParseProcStatCPU(const std::string& input);
251 // Get the number of threads of |process| as available in /proc/<pid>/stat.
252 // This should be used with care as no synchronization with running threads is
253 // done. This is mostly useful to guarantee being single-threaded.
254 // Returns 0 on failure.
255 BASE_EXPORT int GetNumberOfThreads(ProcessHandle process);
257 // /proc/self/exe refers to the current executable.
258 BASE_EXPORT extern const char kProcSelfExe[];
260 // Data from /proc/meminfo about system-wide memory consumption.
261 // Values are in KB.
262 struct BASE_EXPORT SystemMemoryInfoKB {
263 SystemMemoryInfoKB();
265 // Serializes the platform specific fields to value.
266 scoped_ptr<Value> ToValue() const;
268 int total;
269 int free;
270 int buffers;
271 int cached;
272 int active_anon;
273 int inactive_anon;
274 int active_file;
275 int inactive_file;
276 int swap_total;
277 int swap_free;
278 int dirty;
280 // vmstats data.
281 int pswpin;
282 int pswpout;
283 int pgmajfault;
285 #ifdef OS_CHROMEOS
286 int shmem;
287 int slab;
288 // Gem data will be -1 if not supported.
289 int gem_objects;
290 long long gem_size;
291 #endif
294 // Parses a string containing the contents of /proc/meminfo
295 // returns true on success or false for a parsing error
296 BASE_EXPORT bool ParseProcMeminfo(const std::string& input,
297 SystemMemoryInfoKB* meminfo);
299 // Parses a string containing the contents of /proc/vmstat
300 // returns true on success or false for a parsing error
301 BASE_EXPORT bool ParseProcVmstat(const std::string& input,
302 SystemMemoryInfoKB* meminfo);
304 // Retrieves data from /proc/meminfo and /proc/vmstat
305 // about system-wide memory consumption.
306 // Fills in the provided |meminfo| structure. Returns true on success.
307 // Exposed for memory debugging widget.
308 BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
310 // Data from /proc/diskstats about system-wide disk I/O.
311 struct BASE_EXPORT SystemDiskInfo {
312 SystemDiskInfo();
314 // Serializes the platform specific fields to value.
315 scoped_ptr<Value> ToValue() const;
317 uint64 reads;
318 uint64 reads_merged;
319 uint64 sectors_read;
320 uint64 read_time;
321 uint64 writes;
322 uint64 writes_merged;
323 uint64 sectors_written;
324 uint64 write_time;
325 uint64 io;
326 uint64 io_time;
327 uint64 weighted_io_time;
330 // Checks whether the candidate string is a valid disk name, [hsv]d[a-z]+
331 // for a generic disk or mmcblk[0-9]+ for the MMC case.
332 // Names of disk partitions (e.g. sda1) are not valid.
333 BASE_EXPORT bool IsValidDiskName(const std::string& candidate);
335 // Retrieves data from /proc/diskstats about system-wide disk I/O.
336 // Fills in the provided |diskinfo| structure. Returns true on success.
337 BASE_EXPORT bool GetSystemDiskInfo(SystemDiskInfo* diskinfo);
338 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
340 #if defined(OS_CHROMEOS)
341 // Data from files in directory /sys/block/zram0 about ZRAM usage.
342 struct BASE_EXPORT SwapInfo {
343 SwapInfo()
344 : num_reads(0),
345 num_writes(0),
346 compr_data_size(0),
347 orig_data_size(0),
348 mem_used_total(0) {
351 // Serializes the platform specific fields to value.
352 scoped_ptr<Value> ToValue() const;
354 uint64 num_reads;
355 uint64 num_writes;
356 uint64 compr_data_size;
357 uint64 orig_data_size;
358 uint64 mem_used_total;
361 // In ChromeOS, reads files from /sys/block/zram0 that contain ZRAM usage data.
362 // Fills in the provided |swap_data| structure.
363 BASE_EXPORT void GetSwapInfo(SwapInfo* swap_info);
364 #endif // defined(OS_CHROMEOS)
366 // Collects and holds performance metrics for system memory and disk.
367 // Provides functionality to retrieve the data on various platforms and
368 // to serialize the stored data.
369 class SystemMetrics {
370 public:
371 SystemMetrics();
373 static SystemMetrics Sample();
375 // Serializes the system metrics to value.
376 scoped_ptr<Value> ToValue() const;
378 private:
379 FRIEND_TEST_ALL_PREFIXES(SystemMetricsTest, SystemMetrics);
381 size_t committed_memory_;
382 #if defined(OS_LINUX) || defined(OS_ANDROID)
383 SystemMemoryInfoKB memory_info_;
384 SystemDiskInfo disk_info_;
385 #endif
386 #if defined(OS_CHROMEOS)
387 SwapInfo swap_info_;
388 #endif
391 } // namespace base
393 #endif // BASE_PROCESS_PROCESS_METRICS_H_