- add sources.
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / core / platform / proc_util.py
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.
4
5 from collections import defaultdict
6
7 try:
8   import resource  # pylint: disable=F0401
9 except ImportError:
10   resource = None  # Not available on all platforms
11
12
13 def _ConvertKbToByte(value):
14   return int(value.replace('kB','')) * 1024
15
16
17 def _GetProcFileDict(contents):
18   retval = {}
19   for line in contents.splitlines():
20     key, value = line.split(':')
21     retval[key.strip()] = value.strip()
22   return retval
23
24
25 def _GetProcJiffies(timer_list):
26   """Parse '/proc/timer_list' output and returns the first jiffies attribute.
27
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(':')
35       return value
36   raise Exception('Unable to find jiffies from /proc/timer_list')
37
38
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']))
45
46
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])
52
53   cpu_process_jiffies = utime + stime
54   if add_children:
55     cpu_process_jiffies += cutime + cstime
56
57   return {'CpuProcessTime': cpu_process_jiffies}
58
59
60 def GetTimestampJiffies(timer_list):
61   """Return timestamp of system in jiffies."""
62   total_jiffies = float(_GetProcJiffies(timer_list))
63   return {'TotalTime': total_jiffies}
64
65
66 def GetMemoryStats(status_contents, stats):
67   status = _GetProcFileDict(status_contents)
68   if not status or not stats or 'Z' in status['State']:
69     return {}
70   return {'VM': int(stats[22]),
71           'VMPeak': _ConvertKbToByte(status['VmPeak']),
72           'WorkingSetSize': int(stats[23]) * resource.getpagesize(),
73           'WorkingSetSizePeak': _ConvertKbToByte(status['VmHWM'])}
74
75
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'])}
82
83
84 def GetChildPids(processes, pid):
85   child_dict = defaultdict(list)
86   for curr_pid, curr_ppid, state in processes:
87     if 'Z' in state:
88       continue  # Ignore zombie processes
89     child_dict[int(curr_ppid)].append(int(curr_pid))
90   queue = [pid]
91   child_ids = []
92   while queue:
93     parent = queue.pop()
94     if parent in child_dict:
95       children = child_dict[parent]
96       queue.extend(children)
97       child_ids.extend(children)
98   return child_ids