Get the number of CPU cores available on the system.
moon add justjavac/num_cpus| Function | Description |
|---|---|
| @num_cpus.get() | Returns the number of logical CPU cores |
| @num_cpus.get_physical() | Returns the number of physical CPU cores, or a fallback value when exact detection is unavailable |
fn main {
let logical = @num_cpus.get()
let physical = @num_cpus.get_physical()
println("Logical CPU cores: \{logical}")
println("Physical CPU cores: \{physical}")
if logical > physical {
println("SMT or hyper-threading is likely enabled")
}
}fn worker_count() -> Int {
@num_cpus.get_physical()
}fn main {
let logical = @num_cpus.get()
let physical = @num_cpus.get_physical()
println("CPU topology: \{physical} physical / \{logical} logical")
}| Platform | Logical CPUs | Physical CPUs | Implementation |
|---|---|---|---|
| Windows | Yes | Yes | GetSystemInfo and GetLogicalProcessorInformation |
| macOS | Yes | Yes | sysconf and sysctl |
| Linux | Yes | Yes | sysconf and /proc/cpuinfo |
| Other Unix-like systems | Yes | Fallback | sysconf, with physical count falling back to logical count |
moon test --target native
moon check --deny-warn --target nativefn get() -> Intlet logical_cores = @num_cpus.get()
println("Logical CPU cores: \{logical_cores}")fn get_physical() -> Intlet physical_cores = @num_cpus.get_physical()
let logical_cores = @num_cpus.get()
println("Physical cores: \{physical_cores}")
println("Logical cores: \{logical_cores}")
println("Hyperthreading ratio: \{logical_cores / physical_cores}")Get the number of CPU cores available on the system.