README: document nit_env.sh
[nit.git] / lib / performance_analysis.nit
1 # This file is part of NIT (http://www.nitlanguage.org).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Services to gather information on the performance of events by categories
16 #
17 # Provides `PerfMap` to manage all the categories and
18 # `PerfEntry` for per-category statistics.
19 #
20 # ~~~
21 # for i in 100.times do
22 # var clock = new Clock
23 #
24 # # Do some "work" here
25 # nanosleep(0, 1000000)
26 #
27 # # Register the perf
28 # sys.perfs["sleep 1ms"].add clock.lapse
29 #
30 # # Do some other "work" here
31 # nanosleep(0, 5000000)
32 #
33 # # Register the perf
34 # sys.perfs["sleep 5ms"].add clock.lapse
35 # end
36 #
37 # assert sys.perfs["sleep 1ms"].count == 100
38 # assert sys.perfs["sleep 1ms"].avg.is_approx(0.001, 0.001)
39 # assert sys.perfs["sleep 5ms"].avg.is_approx(0.005, 0.005)
40 # ~~~
41 module performance_analysis
42
43 import realtime
44
45 redef class Sys
46 # Main `PerfMap` available by default
47 var perfs = new PerfMap
48 end
49
50 # Collection of statistics on many events
51 class PerfMap
52 super HashMap[String, PerfEntry]
53
54 redef fun provide_default_value(key)
55 do
56 if not key isa String then return super
57
58 var ts = new PerfEntry(key)
59 self[key] = ts
60 return ts
61 end
62
63 redef fun to_s do return "* " + join("\n* ", ": ")
64 end
65
66 # Statistics on wall clock execution time of a category of events by `name`
67 class PerfEntry
68
69 # Name of the category
70 var name: String
71
72 # Shortest execution time of registered events
73 var min = 0.0
74
75 # Longest execution time of registered events
76 var max = 0.0
77
78 # Average execution time of registered events
79 var avg = 0.0
80
81 # Number of registered events
82 var count = 0
83
84 # Total execution time of this event
85 var sum = 0.0
86
87 # Register a new event execution time with a `Timespec`
88 fun add(lapse: Timespec) do add_float lapse.to_f
89
90 # Register a new event execution time in seconds using a `Float`
91 fun add_float(time: Float)
92 do
93 if time.to_f < min.to_f or count == 0 then min = time
94 if time.to_f > max.to_f then max = time
95
96 sum += time
97 count += 1
98 avg = sum / count.to_f
99 end
100
101 redef fun to_s do return "min {min}, max {max}, avg {avg}, sum {sum}, count {count}"
102 end