xref: /aosp_15_r20/external/webrtc/tools_webrtc/cpu/cpu_mon.py (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1#!/usr/bin/env vpython3
2#
3# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
4#
5# Use of this source code is governed by a BSD-style license
6# that can be found in the LICENSE file in the root of the source
7# tree. An additional intellectual property rights grant can be found
8# in the file PATENTS.  All contributing project authors may
9# be found in the AUTHORS file in the root of the source tree.
10
11import sys
12
13import psutil
14import numpy
15from matplotlib import pyplot
16
17
18class CpuSnapshot:
19  def __init__(self, label):
20    self.label = label
21    self.samples = []
22
23  def Capture(self, sample_count):
24    print(('Capturing %d CPU samples for %s...' %
25           ((sample_count - len(self.samples)), self.label)))
26    while len(self.samples) < sample_count:
27      self.samples.append(psutil.cpu_percent(1.0, False))
28
29  def Text(self):
30    return (
31        '%s: avg=%s, median=%s, min=%s, max=%s' %
32        (self.label, numpy.average(self.samples), numpy.median(
33            self.samples), numpy.min(self.samples), numpy.max(self.samples)))
34
35  def Max(self):
36    return numpy.max(self.samples)
37
38
39def GrabCpuSamples(sample_count):
40  print('Label for snapshot (enter to quit): ')
41  label = eval(input().strip())
42  if len(label) == 0:
43    return None
44
45  snapshot = CpuSnapshot(label)
46  snapshot.Capture(sample_count)
47
48  return snapshot
49
50
51def main():
52  print('How many seconds to capture per snapshot (enter for 60)?')
53  sample_count = eval(input().strip())
54  if len(sample_count) > 0 and int(sample_count) > 0:
55    sample_count = int(sample_count)
56  else:
57    print('Defaulting to 60 samples.')
58    sample_count = 60
59
60  snapshots = []
61  while True:
62    snapshot = GrabCpuSamples(sample_count)
63    if snapshot is None:
64      break
65    snapshots.append(snapshot)
66
67  if len(snapshots) == 0:
68    print('no samples captured')
69    return -1
70
71  pyplot.title('CPU usage')
72
73  for s in snapshots:
74    pyplot.plot(s.samples, label=s.Text(), linewidth=2)
75
76  pyplot.legend()
77
78  pyplot.show()
79  return 0
80
81
82if __name__ == '__main__':
83  sys.exit(main())
84