How to get the number of cores on a machine with OCaml?

I am parallelizing some work in my OCaml program (s parmap), but I would prefer not to write the number of cores to my application. Is there a way to get the number of cores at runtime? I would prefer not to add any dependencies (nothing but parmapJS core). I have a feeling that I stopped looking for a simple call in stdlib ...

EDIT: It should not be portable. Work on Linux is good enough.

+5
source share
1 answer

I once had the same question. This is what I eventually came up with (I didn't want to associate C):

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

Unix, open_process_in Sys.command . linux osx, , mingw, cygwin .

. , freebsd, , , sysctl -n hw.ncpu. , Sys.os_type , uname -s, Sys.os_type Win32.

+8

All Articles