Plotting resource usage statistics
Using monitor
to generate CPU and memory use statistics for a process and its children:
monitor -i 0.2 -o /tmp/usage.tsv 'ebk-find -n'
Here I am using ebk-find
with fzf
as the selection command.
The Monitor output looks like this:
Time | CPU% | Threads | RSS | VMS | PID | Process | Command |
---|---|---|---|---|---|---|---|
0.00 | 0.0 | 1 | 8.250 | 18.711 | 137016 | ebk-find | …/python …/ebk-find -n |
0.10 | 76.7 | 1 | 18.125 | 27.641 | 137016 | ebk-find | …/python …/ebk-find -n |
0.10 | 0.0 | 10 | 6.375 | 1850.371 | 137017 | fzf | fzf |
0.20 | 0.0 | 1 | 18.125 | 27.641 | 137016 | ebk-find | …/python …/ebk-find -n |
0.20 | 0.0 | 10 | 6.375 | 1850.371 | 137017 | fzf | fzf |
Read the data into Python using Pandas:
import pandas as pd
data = pd.read_table("/tmp/usage.tsv")
grouped = data.groupby("Process")
Set up a figure for Matplotlib to plot to, with two subplots: one for CPU usage and one for memory:
import matplotlib.pyplot as plt
plt.style.use("bmh")
fig = plt.figure(figsize=(6, 6), layout="constrained")
mem, cpu = fig.subplots(nrows=2, sharex=True)
For each process in the table, plot the CPU usage against time:
for cmd, subset in grouped:
cpu.plot("Time", "CPU%", "o-", data=subset, label=cmd)
cpu.set_xlabel("Time, s")
cpu.set_ylabel("CPU, %")
Plot the memory usage (RSS or VMS) against time in the other subplot. Since we have a shared x-axis, we don’t set an x label this time.
for cmd, subset in grouped:
mem.plot("Time", "RSS", "o-", data=subset, label=cmd)
mem.set_ylabel("RSS memory, MiB")
Add the legend to one of the subplots (whichever has the most white space):
cpu.legend()
Then save the figure to file:
fig.savefig("/tmp/usage.svg", transparent=True)