Created
October 9, 2023 06:32
-
-
Save encima/c1c677c2d8637df5c93056e996568c84 to your computer and use it in GitHub Desktop.
CPU Usage Visualization using Bokeh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import psutil | |
from bokeh.plotting import figure, show | |
from bokeh.io import curdoc | |
from bokeh.models import ColumnDataSource | |
from bokeh.layouts import layout | |
from threading import Thread | |
# Prepare empty data source | |
source = ColumnDataSource(data=dict(time=[], cpu=[])) | |
# Create a new plot | |
p = figure(height=500, width=800, title="CPU Usage Monitor", | |
x_axis_label='Time', y_axis_label='CPU Usage (%)', | |
x_axis_type='datetime') | |
# Add lines to the plot | |
p.line(x='time', y='cpu', color='blue', legend_label="CPU Usage", alpha=0.5, source=source) | |
# Create a callback function to update the ColumnDataSource every second | |
def update(): | |
t = time.time() * 1000 # current time | |
cpu_percent = psutil.cpu_percent() # CPU usage stats | |
new_data = dict(time=[t], cpu=[cpu_percent]) | |
source.stream(new_data) # stream the new data to the source | |
# Use curdoc to add the plot to the document | |
curdoc().add_root(layout([p])) | |
# Add a periodic_callback, which will call the update function every 1000 milliseconds | |
curdoc().add_periodic_callback(update, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment