Created
April 11, 2018 08:42
-
-
Save danhper/b2d2a9af10c4615b658db95257b8f03b to your computer and use it in GitHub Desktop.
Sample usage of OCaml parmap library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(**************************************************************************) | |
(* Sample usage of OCaml parmap library *) | |
(* https://github.com/rdicosmo/parmap *) | |
(* *) | |
(* Computes pi using a simple approximation *) | |
(* \frac{\pi}{4} = \sum_{n=0}^{\infty} \frac{(-1)^n}{2n + 1} *) | |
(* *) | |
(* Compile with the following command: *) | |
(* ocamlfind ocamlopt -linkpkg -package parmap parmap_sample.ml *) | |
(**************************************************************************) | |
let compute_pi start stop = | |
let rec loop n sum = | |
if n >= stop then sum | |
else | |
let v = float (1 - (n mod 2) * 2) /. float (2 * n + 1) in | |
loop (n + 1) (sum +. v) | |
in | |
4. *. (loop start 0.) | |
let () = | |
let max_val = 10000000000 in | |
let nproc = Parmap.get_default_ncores () in | |
let step = max_val / nproc in | |
let parts = Array.mapi (fun i v -> i * step) (Array.init nproc (fun x -> x)) in | |
let parts_seq = Parmap.A parts in | |
let results = Parmap.parmap (fun v -> compute_pi v (v + step - 1)) parts_seq in | |
let pi = List.fold_left ((+.)) 0. results in | |
print_endline (string_of_float pi) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment