Skip to content

Instantly share code, notes, and snippets.

@hkoba
Created April 9, 2014 14:46
Show Gist options
  • Save hkoba/10278837 to your computer and use it in GitHub Desktop.
Save hkoba/10278837 to your computer and use it in GitHub Desktop.
Just to prove OCaml's gc can collect self referencing record.
## Test array size=1048576
(filled - start).live_words = 6291460
(end - filled).live_words = -6291452
(end - start).live_words = 8
(filled - start).live_blocks = 2097153
(end - filled).live_blocks = -2097151
(end - start).live_blocks = 2
(* -*- coding: utf-8 -*- *)
open Core.Std
type 'a t = {value: 'a; mutable prev: 'a t; mutable next: 'a t}
let init value =
let rec x = {value; prev = x; next = x} in
x
type stat_log_t =
{sl_live_words: int; sl_live_blocks: int; sl_msg: string}
let gc_stat msg =
let open Gc.Stat in
Gc.full_major ();
let {live_words; live_blocks; _} = Gc.stat () in
{sl_msg = msg; sl_live_words = live_words; sl_live_blocks = live_blocks}
let () =
let default_nobjs = 1024*1024
in
let nobjs =
if (Array.length Sys.argv) <= 1 then
default_nobjs
else
int_of_string Sys.argv.(0)
in
Printf.printf "## Test array size=%d\n" nobjs;
let holder = Array.init nobjs ~f:(fun _ -> None)
in
let at_start =
gc_stat "# Just after the array is initialized with None:"
in
for i = 0 to nobjs - 1 do
holder.(i) <- Some (init i)
done;
let at_filled =
gc_stat "# After the array is filled with selfref records:"
in
for i = 0 to nobjs - 1 do
holder.(i) <- None
done;
let at_end =
gc_stat "# After the array is cleared with None:"
in
Printf.printf "(filled - start).live_words = %d\n"
(at_filled.sl_live_words - at_start.sl_live_words);
Printf.printf "(end - filled).live_words = %d\n"
(at_end.sl_live_words - at_filled.sl_live_words);
Printf.printf "(end - start).live_words = %d\n"
(at_end.sl_live_words - at_start.sl_live_words);
Printf.printf "(filled - start).live_blocks = %d\n"
(at_filled.sl_live_blocks - at_start.sl_live_blocks);
Printf.printf "(end - filled).live_blocks = %d\n"
(at_end.sl_live_blocks - at_filled.sl_live_blocks);
Printf.printf "(end - start).live_blocks = %d\n"
(at_end.sl_live_blocks - at_start.sl_live_blocks);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment