code / lua-sampleprof

Lines181 C91 Lua48 make25 Markdown17
(56 lines)
1 local sample = require('sampleprof')
3 local foo = function()
4 for i=1,1000 do
5 i = i + 1
6 end
7 end
9 local baz = function()
10 for i=1,500 do
11 i = i + 1
12 end
13 end
15 collectgarbage('stop')
16 local profile = sample(1,100,function(n)
17 assert(n == 23)
18 for i=1,1000 do
19 foo()
20 baz()
21 end
22 end, 23)
24 assert(profile)
26 -- Print a heatmap of the results:
27 if arg[1] == '-p' then
28 local f = io.open('test.lua')
29 local maxline = 0
30 local lines = {}
31 for i=1,9999 do
32 local line = f:read("l")
33 if not line then break end
34 lines[i] = line
35 maxline = math.max(#line, maxline)
36 end
38 local max, total = 0, 0
39 for k,v in pairs(profile) do
40 local filename = k:match("([^:]*):")
41 if filename == 'test.lua' then
42 max = math.max(max, v)
43 total = total + v
44 end
45 end
47 for i, line in ipairs(lines) do
48 local count = (profile[("test.lua:%d"):format(i)] or 0)
49 local percentmax = count/(max+1)
50 local k = math.floor(6*percentmax^.25)
51 local r,g,b = k+math.min(k,5-k),5-k+math.min(k,5-k),0
52 if count == 0 then r,g,b = 2,2,1 end
53 local color = 16+36*r+6*g+b
54 print(("\x1b[2m%3d\x1b[0m \x1b[38;5;%dm%s%s\x1b[0m"):format(i, color, line, (" "):rep(maxline-#line)))
55 end
56 end