Paste: silly benchmark in more idiomatic OCaml

Author: anon
Mode: ml
Date: Sat, 29 Aug 2009 15:21:58
Plain Text |
(* functional solution without array mutation, could be made faster by using
 * array mutation
 *
 * on AMD64, 
 * 3.1 secs for OCaml 3.11.1
 *   (-nodynlink -inline 100, with OCAMLRUNPARAM=h=70M to set the heap size)
 * 8.3 secs for silly.java (java -Xms512m -server)
 *     Java HotSpot(TM) 64-Bit Server VM (build 10.0-b19, mixed mode)
 * *)

open Printf

type point = { x : float; y : float; z : float }

let makePoint n =
  let fn = float_of_int n in
  let x = sin fn in
  let y = 3.0 *. cos fn in
  let z = let s = sin fn in s *. s /. 2.0 in
    {x = x; y = y; z = z}

let toString p = sprintf "%f, %f, %f" p.x p.y p.z

let makePoints n = Array.init n makePoint

let pointNorm p = p.x *. p.x +. p.y *. p.y +. p.z *. p.z

let normalizePoint p =
  let norm = pointNorm p in
    { x = p.x /. norm; y = p.y /. norm; z = p.z /. norm }

let normalizePoints arr = Array.map normalizePoint arr

let max (x : float) y = if x < y then y else x

let maxPoint p1 p2 = { x = max p1.x p2.x; y = max p1.y p2.y; z = max p1.z p2.z }

let maxPoints arr = Array.fold_left (fun max c -> maxPoint max c) arr.(0) arr

let benchmark n = 
  print_endline (toString (maxPoints (normalizePoints (makePoints n))))

let runBenchmark () = 
  Gc.compact ();
  for n = 1 to 8 do
    printf "Run #%d\n%!" n;
    let t1 = Sys.time () in
      benchmark 5000000;
      let t2 = Sys.time () in
        printf "Time: %f\n%!" (t2 -. t1)
  done

let () = runBenchmark ()

New Annotation

Summary:
Author:
Mode:
Body: