A Moonbit module to get the number of CPU cores available on the system.
https://github.com/justjavac/moonbit-num-cpus.git
A MoonBit module to get the number of CPU cores available on the system, supporting both logical and physical core detection.
Add justjavac/num_cpus to your dependencies:
moon update
moon add justjavac/num_cpus
fn main {
let logical_cpus = @num_cpus.get()
let physical_cpus = @num_cpus.get_physical()
println("Logical CPU cores: \{logical_cpus}")
println("Physical CPU cores: \{physical_cpus}")
if logical_cpus > physical_cpus {
println("Hyperthreading/SMT is enabled")
}
}
| Platform | Logical CPUs | Physical CPUs | Implementation |
|---|---|---|---|
| Windows | β | β | Win32 API (GetSystemInfo, GetLogicalProcessorInformation) |
| macOS | β | β | POSIX (sysconf) + BSD (sysctlbyname) |
| Linux | β | β | POSIX (sysconf) + /proc/cpuinfo parsing |
| Other Unix | β | β οΈ | POSIX (sysconf), falls back to logical count |
The native implementation uses C FFI to call platform-specific system APIs:
// Windows
int moonbit_get_cpu_count(); // GetSystemInfo
int moonbit_get_physical_cpu_count(); // GetLogicalProcessorInformation
// Unix-like systems
int moonbit_get_cpu_count(); // sysconf(_SC_NPROCESSORS_ONLN)
int moonbit_get_physical_cpu_count(); // Platform-specific implementations
sysconf() on Unix systems andGetSystemInfo() on Windows
fn main {
println("CPU cores: \{@num_cpus.get()}")
}
fn main {
let logical = @num_cpus.get()
let physical = @num_cpus.get_physical()
let ratio = logical.to_double() / physical.to_double()
if ratio == 1.0 {
println("No hyperthreading detected")
} else if ratio == 2.0 {
println("2x hyperthreading (common)")
} else {
println("SMT ratio: \{ratio}")
}
}
fn get_optimal_thread_count() -> Int {
let logical = @num_cpus.get()
let physical = @num_cpus.get_physical()
// Use physical cores for CPU-bound tasks
// Use logical cores for I/O-bound tasks
// This is just an example - you'd implement is_cpu_bound_workload()
physical // Simplified example
}
MIT License - see LICENSE file for details.
num_cpus