Get CPU usage

Is there any built-in function that I can use to get the CPU usage of PCs? I’m writing a load balancer that orchestrates multiple PCs to perform a computation task based on CPU and memory usage. I know other languages like Python can do this but I’m not sure if Julia can?

I don’t know about a julia library to do it.

I’ve done it with the psutil python library.

You can use the Conda package (or PyCall I guess) to do it. Example

julia> using Conda
julia> Conda.add("psutil")

julia> aux = py"""import psutil
       def get_cpu():
           return psutil.cpu_percent()
       """

julia> py"get_cpu()"
11.3
julia> x = py"get_cpu()"
8.1
julia> typeof(x)
Float64
7 Likes

Thank you David! It helps!

Hope someone can give a Julia way of this!

1 Like

If you are using Linux, you can query and parse /proc/stat, eg

function get_cpu_stats()
    st = read("/proc/stat", String)
    m = match(r"^cpu *(.*)", st)
    parse.(Int, split(m.captures[1], ' '))
end

Then take the difference between two calls with a bit of time between them, and use the relevant fields to calculate the stats you want to focus on (this depends on your architecture and application, eg whether you consider IO wait times relevant, etc). See proc(5) for the format.

3 Likes

I note that on the psutil GitHub page there are links to ports in Go, Rust etc.
Surely we cannot let these languages have something we do not…
To the barricades mes amis!

2 Likes

I appreciate your enthusiasm, but replicating psutil is a lot of tedious work, that requires ongoing fixes and updates, and access to a diverse set of OS environments (both for development and CI).

I am totally fine with this effort being centralized, and just calling eg the original python library via a foreign function interface. External dependencies are not ideal, but in this case they may be the easiest solution. These kind of queries are rarely performance-critical anyway.

2 Likes

The psutil code was not too hard to port to Julia:

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
	)

period = 3 # seconds

usages = let
	
	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


	busies ./ (idles .+ busies)
end

# This returns a Vector{Float64} with the CPU usage between 0.0 and 1.0
6 Likes

Your advice was very helpful.
I could implement an easy application using MiniFB.jl and Plots.jl

1 Like