Skip to content

Commit e57a0e8

Browse files
Display average CPU usage if user's machine has many cores
1 parent b3c838e commit e57a0e8

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/TerminalSystemMonitor.jl

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ using Dates: Dates, Day, DateTime, Second
44
using UnicodePlots
55
import Term # this is required by UnicodePlots.panel
66
using Term: Consoles
7+
using Statistics: mean
78
using MLDataDevices: MLDataDevices, CUDADevice, CPUDevice, MetalDevice
89

910
export monitor # entrypoint from REPL
@@ -83,6 +84,15 @@ function plot_cpu_utilization_rates(::Type{CPUDevice})
8384
ys = get_cpu_percent()
8485
npad = 1 + floor(Int, log10(length(ys)))
8586
xs = ["id: $(lpad(i-1, npad))" for (i, _) in enumerate(ys)]
87+
function plot_cpu_utilization_rates(::Type{CPUDevice}, statfn=identity)
88+
ys = statfn(get_cpu_percent())
89+
if !(ys isa AbstractVector)
90+
xs = ["CPU: " * string(statfn)]
91+
ys = [ys]
92+
else
93+
npad = 1 + floor(Int, log10(length(ys)))
94+
xs = ["id: $(lpad(i-1, npad))" for (i, _) in enumerate(ys)]
95+
end
8696

8797
ncpus = length(ys)
8898
ys = round.(ys, digits = 1)
@@ -136,13 +146,14 @@ function main(dummyargs...)
136146
# Control cursor hiding and showing with Term.Consoles
137147
Consoles.hide_cursor()
138148

149+
statfn = identity
139150
while true
140151
try
141-
_, cols = displaysize(stdout)
152+
rows, cols = displaysize(stdout)
142153
t1 = @async begin
143154
try
144155
plts = []
145-
append!(plts, plot_cpu_utilization_rates(CPUDevice))
156+
append!(plts, plot_cpu_utilization_rates(CPUDevice, statfn))
146157
n = max(1, cols ÷ 25)
147158
chunks = collect(Iterators.partition(plts, n))
148159
f = foldl(/, map(c -> prod(UnicodePlots.panel.(c)), chunks))
@@ -226,6 +237,16 @@ function main(dummyargs...)
226237

227238
Consoles.move_to_line(stdout, 1)
228239
Consoles.cleartoend(stdout)
240+
# If user's machine has lots of CPU cores, we can't fit all the plots in one screen.
241+
# So we need to use `mean` function to reduce the number of plots.
242+
if length(split(string(f), "\n")) > rows
243+
statfn = mean
244+
end
245+
246+
# If terminal has enough space, we can use `identity` function again to show all the plots.
247+
if rows > 2length(split(string(f), "\n"))
248+
statfn = identity
249+
end
229250
display(f)
230251
catch e
231252
Consoles.show_cursor()

0 commit comments

Comments
 (0)