I'm parallelizing some work in my OCaml program (with parmap
) but I would prefer not to hard code the number of cores into my application. Is there a way to get the number of cores at runtime? I would prefer not to add any more dependencies (nothing beyond parmap
or JS's core
). I have a feeling I'm over looking some simple call in stdlib...
EDIT: it doesn't have to be portable. Working on linux is good enough.
I once had the same question. That's what I eventually came with (I didn't want C bindings):
let cpu_count () =
try match Sys.os_type with
| "Win32" -> int_of_string (Sys.getenv "NUMBER_OF_PROCESSORS")
| _ ->
let i = Unix.open_process_in "getconf _NPROCESSORS_ONLN" in
let close () = ignore (Unix.close_process_in i) in
try Scanf.fscanf i "%d" (fun n -> close (); n) with e -> close (); raise e
with
| Not_found | Sys_error _ | Failure _ | Scanf.Scan_failure _
| End_of_file | Unix.Unix_error (_, _, _) -> 1
If you don't want Unix
you could replace open_process_in
by a Sys.command
writing to a temporary file. Tested on linux and osx, reported to work on mingw but not on cygwin at the time.
Update. Note that this doesn't work on freebsd where as mentioned here you need to use
sysctl -n hw.ncpu
. However since Sys.os_type
doesn't have the right granularity you'd need to conditionalize on the result of uname -s
whenever Sys.os_type
is different from Win32
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With