Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Loop times
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Daniel M. Albro <albro@h...>
Subject: [Caml-list] Loop times

	OK, I just did a test of the three methods.  Here's the code:

Exception Version:
-------------------------------------------------
exception Break

let _ =
  let ary = [|1;2;3;4;5;6;7;8;9;10;11;12|] in
    for i = 1 to 1_000_000_000 do
      try
        for j = 1 to 10 do
          if ary.(j) = 5 then
            raise Break
        done
      with Break -> ()
    done

real    0m30.569s
user    0m30.250s
sys     0m0.140s
------------------------------------------------------

Straight imperative version:
------------------------------------------------------
let _ =
  let ary = [|1;2;3;4;5;6;7;8;9;10;11;12|] in
  let j = ref 0 in
    for i = 1 to 1_000_000_000 do
      j := 0;
      while !j < 10 do
        if ary.(!j) = 5 then
          j := 10;
        incr j
      done
    done

real    0m40.498s
user    0m39.980s
sys     0m0.260s
------------------------------------------------------

Tail recursive version:
------------------------------------------------------
let _ =
  let ary = [|1;2;3;4;5;6;7;8;9;10;11;12|] in
  let rec loop j =
    if j = 10 then 
      ()
    else if ary.(j) = 5 then
      ()
    else
      loop (j + 1)
  in
    for i = 1 to 1_000_000_000 do
      loop 1
    done

real    0m22.571s
user    0m22.360s
sys     0m0.080s
-------------------------------------------------------

	So may I should just be quiet and use
recursion :).

-- 
Daniel M. Albro <albro@humnet.ucla.edu>

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners