-
Notifications
You must be signed in to change notification settings - Fork 0
/
measure_advanced.lua
85 lines (70 loc) · 1.64 KB
/
measure_advanced.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
local get_time = require("debug.get_time")
local function get_median(tbl, start, stop)
start = start or 1
stop = stop or #tbl
local new = {}
for i = start, stop do
table.insert(new, tbl[i])
end
table.sort(new)
local median = new[math.ceil(#new / 2)] or new[1]
return median
end
local function get_average(tbl, start, stop)
start = start or 1
stop = stop or #tbl
if #tbl == 0 then return nil end
local n = 0
local count = 0
for i = start, stop do
n = n tbl[i]
count = count 1
end
return n / count
end
return function(what, cb) -- type util.Measure = function(string, function): any
local space = (" "):rep(40 - #what)
io.write("> ", what, "\n")
local times = {}
local threshold = 0.01
local lookback = 5
for i = 1, 30 do
local time = get_time()
local ok, err = pcall(cb)
times[i] = get_time() - time
io.write(("%.5f"):format(times[i]), " seconds\n")
if i >= lookback and times[i] > 0.5 then
local current = get_average(times)
local latest = get_average(times, #times - lookback 1)
local diff = math.abs(current - latest)
if diff > 0 and diff < threshold then
io.write(
"time difference the last ",
lookback,
" times (",
diff,
") met the threshold (",
threshold,
"), stopped measuring.\n"
)
break
end
end
if not ok then
io.write(" - FAIL: ", err)
error(err, 2)
end
end
local average = get_average(times)
local median = get_median(times)
table.sort(times)
local min = times[1]
local max = times[#times]
io.write(
"< FINISHED: ",
("%.5f"):format(median),
" seconds (median), ",
("%.5f"):format(average),
" seconds (average)\n"
)
end