1 # Copyright 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 from collections import defaultdict
8 import resource # pylint: disable=F0401
10 resource = None # Not available on all platforms
13 def _ConvertKbToByte(value):
14 return int(value.replace('kB','')) * 1024
17 def _GetProcFileDict(contents):
19 for line in contents.splitlines():
20 key, value = line.split(':')
21 retval[key.strip()] = value.strip()
25 def _GetProcJiffies(timer_list):
26 """Parse '/proc/timer_list' output and returns the first jiffies attribute.
28 Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be
29 essentially the same. Return the first one."""
30 if isinstance(timer_list, str):
31 timer_list = timer_list.splitlines()
32 for line in timer_list:
33 if line.startswith('jiffies:'):
34 _, value = line.split(':')
36 raise Exception('Unable to find jiffies from /proc/timer_list')
39 def GetSystemCommitCharge(meminfo_contents):
40 meminfo = _GetProcFileDict(meminfo_contents)
41 return (_ConvertKbToByte(meminfo['MemTotal'])
42 - _ConvertKbToByte(meminfo['MemFree'])
43 - _ConvertKbToByte(meminfo['Buffers'])
44 - _ConvertKbToByte(meminfo['Cached']))
47 def GetCpuStats(stats, add_children=False):
48 utime = float(stats[13])
49 stime = float(stats[14])
50 cutime = float(stats[15])
51 cstime = float(stats[16])
53 cpu_process_jiffies = utime + stime
55 cpu_process_jiffies += cutime + cstime
57 return {'CpuProcessTime': cpu_process_jiffies}
60 def GetTimestampJiffies(timer_list):
61 """Return timestamp of system in jiffies."""
62 total_jiffies = float(_GetProcJiffies(timer_list))
63 return {'TotalTime': total_jiffies}
66 def GetMemoryStats(status_contents, stats):
67 status = _GetProcFileDict(status_contents)
68 if not status or not stats or 'Z' in status['State']:
70 return {'VM': int(stats[22]),
71 'VMPeak': _ConvertKbToByte(status['VmPeak']),
72 'WorkingSetSize': int(stats[23]) * resource.getpagesize(),
73 'WorkingSetSizePeak': _ConvertKbToByte(status['VmHWM'])}
76 def GetIOStats(io_contents):
77 io = _GetProcFileDict(io_contents)
78 return {'ReadOperationCount': int(io['syscr']),
79 'WriteOperationCount': int(io['syscw']),
80 'ReadTransferCount': int(io['rchar']),
81 'WriteTransferCount': int(io['wchar'])}
84 def GetChildPids(processes, pid):
85 child_dict = defaultdict(list)
86 for curr_pid, curr_ppid, state in processes:
88 continue # Ignore zombie processes
89 child_dict[int(curr_ppid)].append(int(curr_pid))
94 if parent in child_dict:
95 children = child_dict[parent]
96 queue.extend(children)
97 child_ids.extend(children)