bench: add "nitc --global" and "nitg --separate" to bench_steps
[nit.git] / src / stats / stats_base.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Helpers for various statistics tools.
18 module stats_base
19
20 import modelbuilder
21
22 redef class ToolContext
23 var opt_dir = new OptionString("Directory where some statistics files are generated", "-d", "--dir")
24 var output_dir: String = "."
25
26 redef init
27 do
28 super
29 self.option_context.add_option(opt_dir)
30 end
31
32 redef fun process_options
33 do
34 super
35 var val = self.opt_dir.value
36 if val != null then
37 val = val.simplify_path
38 val.mkdir
39 self.output_dir = val
40 end
41 end
42 end
43
44 # A counter counts occurence of things
45 # Use this instead of a HashMap[E, Int]
46 class Counter[E: Object]
47 # Total number of counted occurences
48 var total: Int = 0
49
50 private var map = new HashMap[E, Int]
51
52 # The number of counted occurences of `e'
53 fun [](e: E): Int
54 do
55 var map = self.map
56 if map.has_key(e) then return map[e]
57 return 0
58 end
59
60 # Count one more occurence of `e'
61 fun inc(e: E)
62 do
63 self.map[e] = self[e] + 1
64 total += 1
65 end
66
67 # Return an array of elements sorted by occurences
68 fun sort: Array[E]
69 do
70 var res = map.keys.to_a
71 var sorter = new CounterSorter[E](self)
72 sorter.sort(res)
73 #res.sort !cmp a, b = map[a] <=> map[b]
74 return res
75 end
76 end
77
78 private class CounterSorter[E: Object]
79 super AbstractSorter[E]
80 var counter: Counter[E]
81 redef fun compare(a,b) do return self.counter.map[a] <=> self.counter.map[b]
82 end
83
84 # Helper function to display n/d and handle division by 0
85 fun div(n: Int, d: Int): String
86 do
87 if d == 0 then return "na"
88 return ((100*n/d).to_f/100.0).to_precision(2)
89 end