Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up OCaml binary trees code #387

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions bench/algorithm/binarytrees/1.ml
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
class node left' right' =
object
val left : node option = left'
module Node = struct
type t = { left : t option; right : t option }

val right : node option = right'
let create left right = { left; right }

method check =
1
+ (match left with None -> 0 | Some l -> l#check)
+ match right with None -> 0 | Some r -> r#check
end
let rec check node =
1
+ (match node.left with None -> 0 | Some l -> check l)
+ match node.right with None -> 0 | Some r -> check r
end

let rec make d =
if d = 0 then new node None None
if d = 0 then Node.create None None
else
let d = d - 1 in
new node (Some (make d)) (Some (make d))
Node.create (Some (make d)) (Some (make d))

let min_depth = 4

Expand All @@ -25,7 +24,7 @@ let max_depth =
let stretch_depth = max_depth + 1

let () =
let c = (make stretch_depth)#check in
let c = Node.check @@ make stretch_depth in
Printf.printf "stretch tree of depth %i\t check: %i\n" stretch_depth c

let long_lived_tree = make max_depth
Expand All @@ -36,13 +35,12 @@ let loop_depths d =
let niter = 1 lsl (max_depth - d + min_depth) in
let c = ref 0 in
for _ = 1 to niter do
c := !c + (make d)#check
c := !c + Node.check (make d)
done;
Printf.printf "%i\t trees of depth %i\t check: %i\n" niter d !c
done

let () =
flush stdout;
loop_depths min_depth;
Printf.printf "long lived tree of depth %i\t check: %i\n" max_depth
long_lived_tree#check
(Node.check long_lived_tree)