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
5 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.

2 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!

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.

1 Like