Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ocaml

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.

like image 761
rgrinberg Avatar asked Apr 29 '13 00:04

rgrinberg


1 Answers

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.

like image 133
Daniel Bünzli Avatar answered Sep 28 '22 09:09

Daniel Bünzli