1"""
2==============
3System Monitor
4==============
5
6"""
7import time
8import matplotlib.pyplot as plt
9import numpy as np
10
11
12def get_memory(t):
13    "Simulate a function that returns system memory"
14    return 100 * (0.5 + 0.5 * np.sin(0.5 * np.pi * t))
15
16
17def get_cpu(t):
18    "Simulate a function that returns cpu usage"
19    return 100 * (0.5 + 0.5 * np.sin(0.2 * np.pi * (t - 0.25)))
20
21
22def get_net(t):
23    "Simulate a function that returns network bandwidth"
24    return 100 * (0.5 + 0.5 * np.sin(0.7 * np.pi * (t - 0.1)))
25
26
27def get_stats(t):
28    return get_memory(t), get_cpu(t), get_net(t)
29
30fig, ax = plt.subplots()
31ind = np.arange(1, 4)
32
33# show the figure, but do not block
34plt.show(block=False)
35
36
37pm, pc, pn = plt.bar(ind, get_stats(0))
38pm.set_facecolor('r')
39pc.set_facecolor('g')
40pn.set_facecolor('b')
41ax.set_xticks(ind)
42ax.set_xticklabels(['Memory', 'CPU', 'Bandwidth'])
43ax.set_ylim([0, 100])
44ax.set_ylabel('Percent usage')
45ax.set_title('System Monitor')
46
47start = time.time()
48for i in range(200):  # run for a little while
49    m, c, n = get_stats(i / 10.0)
50
51    # update the animated artists
52    pm.set_height(m)
53    pc.set_height(c)
54    pn.set_height(n)
55
56    # ask the canvas to re-draw itself the next time it
57    # has a chance.
58    # For most of the GUI backends this adds an event to the queue
59    # of the GUI frameworks event loop.
60    fig.canvas.draw_idle()
61    try:
62        # make sure that the GUI framework has a chance to run its event loop
63        # and clear any GUI events.  This needs to be in a try/except block
64        # because the default implementation of this method is to raise
65        # NotImplementedError
66        fig.canvas.flush_events()
67    except NotImplementedError:
68        pass
69
70stop = time.time()
71print("{fps:.1f} frames per second".format(fps=200 / (stop - start)))
72