vendredi 27 juin 2014

Ocaml Optimization Techniques


Vote count:

0




I am new to Ocaml (with some prior knowledge in Haskell). And I want to persuade myself to adopt Ocaml. Therefore I tried to compare the performance between C and Ocaml. I wrote the following naïve Monte Carlo Pi-finder:


C Version



#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char * argv[]) {

const int N = 10000000;
const int M = 10000000;

int count = 0;
for (int i = 0; i < N; i++) {
double x = (double)(random() % (2 * M + 1) - M) / (double)(M);
double y = (double)(random() % (2 * M + 1) - M) / (double)(M);
if (x * x + y * y <= 1) {
count++;
}
}

double pi_approx = 4.0 * (double)(count) / (double)(N);
printf("pi .= %f", pi_approx);
return 0;
}


Ocaml Version



let findPi m n =
let rec countPi count = function
| 0 -> count
| n ->
let x = float_of_int (Random.int (2 * m + 1) - m) /. (float_of_int m) in
let y = float_of_int (Random.int (2 * m + 1) - m) /. (float_of_int m) in
if x *. x +. y *. y <= 1. then
countPi (count + 1) (n - 1)
else
countPi count (n - 1) in
4.0 *. (float_of_int (countPi 0 n)) /. (float_of_int n);;

let n = 10000000 in
let m = 10000000 in

let pi_approx = findPi m n in
Printf.printf "pi .= %f" pi_approx


I compiled the C with Clang (Apple LLVM version 5.1) and the Ocaml with OCamlopt v4.01.0.


The running time of C is 0.105s. The Ocaml one is 0.945s, which is 9 times slower. My target is to reduce the running time of Ocaml by 3 times, so that the program can finish within 0.315s.


As I am so new to Ocaml, I want to learn some Ocaml optimization techniques. Please leave me some suggestions! (Tail-resursion is already applied)



asked 29 secs ago






Aucun commentaire:

Enregistrer un commentaire