WIP on beautyfying the pretty-printing module.
[SXSI/xpathcomp.git] / src / utils.ml
1 module String =
2 struct
3   include String
4
5   let explode s sep =
6     let len = length s in
7     let buff = Buffer.create 40 in
8     let rec loop i =
9       if i >= len then
10         [ Buffer.contents buff ]
11       else
12         let c = s.[i] in
13         if c == sep then
14           let ss = Buffer.contents buff in
15           Buffer.clear buff;
16           ss :: loop (i+1)
17         else begin
18           Buffer.add_char buff c;
19           loop (i+1);
20         end
21     in
22     loop 0
23 end
24 ;;
25
26 module System =
27 struct
28   let status () =
29     let pid = Unix.getpid() in
30     let cin = open_in (Printf.sprintf "/proc/%i/status" pid) in
31     let h = Hashtbl.create 17 in
32     try
33       while true do
34         let s = input_line cin in
35         Scanf.sscanf s "%s@: %s@\n" (fun k v ->
36           Hashtbl.replace h k v)
37       done;
38       (* never reached *)
39       h
40     with
41       End_of_file -> begin
42         close_in cin;
43         h
44       end
45   let get_status s = Hashtbl.find (status()) s
46
47   let pr_mem_status fmt h =
48     Format.fprintf fmt "[";
49     List.iter (fun k ->
50       let v = Hashtbl.find h k in
51       Format.fprintf fmt "%s= %s " k v
52     ) [ "VmStk"; "VmRSS"; "VmPeak" ];
53     Format.fprintf fmt "]"
54
55 end
56 (*
57 let time f ?(count=1) ?(msg="") x =
58   if not !Options.verbose then f x
59   else
60   let rec loop i =
61     Gc.compact();
62     let oldmem = System.status () in
63     let t1 = Unix.gettimeofday () in
64     let r = f x in
65     let t2 = Unix.gettimeofday () in
66     let newmem = System.status () in
67     let t = (1000. *. (t2 -. t1)) in
68     Logger.verbose Format.err_formatter "%s: " msg;
69     if (count != 1) then Logger.verbose Format.err_formatter "run %i/%i,  "  i count;
70     Logger.verbose
71       Format.err_formatter
72       "%fms (before: %a, after: %a)@\n" t System.pr_mem_status oldmem System.pr_mem_status newmem;
73     if i >= count then r
74     else loop (i+1)
75   in
76   loop 1
77   
78 ;;
79 *)