Skip to content

Instantly share code, notes, and snippets.

@terasakisatoshi
Last active December 3, 2022 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terasakisatoshi/80fcddfe37eeb8263e465a814c2cc624 to your computer and use it in GitHub Desktop.
Save terasakisatoshi/80fcddfe37eeb8263e465a814c2cc624 to your computer and use it in GitHub Desktop.
animate your CPU usge Plots.jl+MiniFB.jl
using MiniFB
using Plots
using Images
using ImageTransformations
const WIDTH = 1200
const HEIGHT = 600
function populate_buffer!(buffer, img)
global WIDTH, HEIGHT
buffer .= zero(UInt32)
h, w = size(img)
ratio = min(1, HEIGHT / h, WIDTH / w)
nimg = imresize(img, ratio = ratio)
nh, nw = size(nimg)
oh = (HEIGHT - nh) ÷ 2
ow = (WIDTH - nw) ÷ 2
for i = 1:nh
for j = 1:nw
buffer[(oh+i-1)*WIDTH+ow+j] = mfb_rgb(nimg[i, j])
end
end
end
idle_time(info::Sys.CPUinfo) = Int64(info.cpu_times!idle)
busy_time(info::Sys.CPUinfo) = Int64(
info.cpu_times!user + info.cpu_times!nice + info.cpu_times!sys + info.cpu_times!irq,
)
"""
cpu_percent(period)
CPU usage between 0.0 and 100 [percent]
The idea is borrowed from https://discourse.julialang.org/t/get-cpu-usage/24468/7
Thank you @fonsp.
"""
function cpu_percent(period::Real = 1.0)
info = Sys.cpu_info()
busies = busy_time.(info)
idles = idle_time.(info)
sleep(period)
info = Sys.cpu_info()
busies = busy_time.(info) .- busies
idles = idle_time.(info) .- idles
100 * busies ./ (idles .+ busies)
end
function main()
window = mfb_open_ex("Plots -> MiniFB", WIDTH, HEIGHT, MiniFB.WF_RESIZABLE)
SECOND = 60
interval = 0.5
tmax = 60
len = ceil(Int, tmax * inv(interval))
history = zeros(length(Sys.cpu_info()), len)
tickstep = Int(tmax * inv(interval) * SECOND)
buffer = zeros(UInt32, HEIGHT * WIDTH)
buf = IOBuffer()
Δelapsed = 0.0
while true
eta = @elapsed begin
period = max(0.0, interval - Δelapsed)
@show period
history[:, begin] .= cpu_percent(period)
stime = time()
p = plot(
range(1,step=interval,length=len),
history',
title = "Get CPU consumption of your machine",
xlabel = "time [sec]",
ylabel = "percent",
legend = :outertopright,
xticks = 0:10:tmax,
xlim = [0, tmax],
ylim = [0, 100],
palette = :tab20c,
size=(WIDTH, HEIGHT),
)
sp = p[1]
for i in axes(history, 1)
sp[i][:label] = "cpuid $i"
end
show(buf, MIME("image/png"), p)
img = buf |> load
take!(buf)
populate_buffer!(buffer, img)
state = mfb_update(window, buffer)
if state != MiniFB.STATE_OK
mfb_close(window)
break
end
history .= circshift(history, (0, 1))
Δelapsed = time() - stime
@show Δelapsed
end
@show eta
end
mfb_close(window)
end
# main()
@terasakisatoshi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment