Debian Codegraph @

texmf-dist/tex/lualatex/luacas/_lib/luacas-pepperfish.lua

raw
1 ---@diagnostic disable: param-type-mismatch, lowercase-global, need-check-nil, assign-type-mismatch
2 --[[
3
4 == Introduction ==
5
6 Note that this requires os.clock(), debug.sethook(),
7 and debug.getinfo() or your equivalent replacements to
8 be available if this is an embedded application.
9
10 Example usage:
11
12 profiler = newProfiler()
13 profiler:start()
14
15 < call some functions that take time >
16
17 profiler:stop()
18
19 local outfile = io.open( "profile.txt", "w+" )
20 profiler:report( outfile )
21 outfile:close()
22
23 == Optionally choosing profiling method ==
24
25 The rest of this comment can be ignored if you merely want a good profiler.
26
27 newProfiler(method, sampledelay):
28
29 If method is omitted or "time", will profile based on real performance.
30 optionally, frequency can be provided to control the number of opcodes
31 per profiling tick. By default this is 100000, which (on my system) provides
32 one tick approximately every 2ms and reduces system performance by about 10%.
33 This can be reduced to increase accuracy at the cost of performance, or
34 increased for the opposite effect.
35
36 If method is "call", will profile based on function calls. Frequency is
37 ignored.
38
39
40 "time" may bias profiling somewhat towards large areas with "simple opcodes",
41 as the profiling function (which introduces a certain amount of unavoidable
42 overhead) will be called more often. This can be minimized by using a larger
43 sample delay - the default should leave any error largely overshadowed by
44 statistical noise. With a delay of 1000 I was able to achieve inaccuray of
45 approximately 25%. Increasing the delay to 100000 left inaccuracy below my
46 testing error.
47
48 "call" may bias profiling heavily towards areas with many function calls.
49 Testing found a degenerate case giving a figure inaccurate by approximately
50 20,000%. (Yes, a multiple of 200.) This is, however, more directly comparable
51 to common profilers (such as gprof) and also gives accurate function call
52 counts, which cannot be retrieved from "time".
53
54 I strongly recommend "time" mode, and it is now the default.
55
56 == History ==
57
58 2021-01-04 - Larry Deaton ( [email protected] )
59 Modified the profiling by "call" operation to ignore internal LUA functions
60 since LUA only provides debug hooks for the calling of the function and not
61 the return of the function. Without this change, the call stack is
62 continually growing.
63
64 2008-09-16 - Time-based profiling and conversion to Lua 5.1
65 by Ben Wilhelm ( [email protected] ).
66 Added the ability to optionally choose profiling methods, along with a new
67 profiling method.
68
69 Converted to Lua 5, a few improvements, and
70 additional documentation by Tom Spilman ( [email protected] )
71
72 Additional corrections and tidying by original author
73 Daniel Silverstone ( [email protected] )
74
75 == Status ==
76
77 Daniel Silverstone is no longer using this code, and judging by how long it's
78 been waiting for Lua 5.1 support, I don't think Tom Spilman is either. I'm
79 perfectly willing to take on maintenance, so if you have problems or
80 questions, go ahead and email me :)
81 -- Ben Wilhelm ( [email protected] ) '
82
83 == Copyright ==
84
85 Lua profiler - Copyright Pepperfish 2002,2003,2004
86
87 Permission is hereby granted, free of charge, to any person obtaining a copy
88 of this software and associated documentation files (the "Software"), to
89 deal in the Software without restriction, including without limitation the
90 rights to use, copy, modify, merge, publish, distribute, and/or sell copies
91 of the Software, and to permit persons to whom the Software is furnished to
92 do so, subject to the following conditions:
93
94 The above copyright notice and this permission notice shall be included in
95 all copies or substantial portions of the Software.
96
97 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
98 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
99 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
100 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
101 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
102 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
103 IN THE SOFTWARE.
104
105 --]]
106
107
108 --
109 -- All profiler related stuff is stored in the top level table '_profiler'
110 --
111 _profiler = {}
112
113
114 --
115 -- newProfiler() creates a new profiler object for managing
116 -- the profiler and storing state. Note that only one profiler
117 -- object can be executing at one time.
118 --
119 function newProfiler(variant, sampledelay)
120 if _profiler.running then
121 print("Profiler already running.")
122 return
123 end
124
125 variant = variant or "time"
126
127 if variant ~= "time" and variant ~= "call" then
128 print("Profiler method must be 'time' or 'call'.")
129 return
130 end
131
132 local newprof = {}
133 for k,v in pairs(_profiler) do
134 newprof[k] = v
135 end
136 newprof.variant = variant
137 newprof.sampledelay = sampledelay or 100000
138 return newprof
139 end
140
141
142 --
143 -- This function starts the profiler. It will do nothing
144 -- if this (or any other) profiler is already running.
145 --
146 function _profiler.start(self)
147 if _profiler.running then
148 return
149 end
150 -- Start the profiler. This begins by setting up internal profiler state
151 _profiler.running = self
152 self.rawstats = {}
153 self.callstack = {}
154 if self.variant == "time" then
155 self.lastclock = os.clock()
156 debug.sethook( _profiler_hook_wrapper_by_time, "", self.sampledelay )
157 elseif self.variant == "call" then
158 debug.sethook( _profiler_hook_wrapper_by_call, "cr" )
159 else
160 print("Profiler method must be 'time' or 'call'.")
161 end
162 end
163
164
165 --
166 -- This function stops the profiler. It will do nothing
167 -- if a profiler is not running, and nothing if it isn't
168 -- the currently running profiler.
169 --
170 function _profiler.stop(self)
171 if _profiler.running ~= self then
172 return
173 end
174 -- Stop the profiler.
175 debug.sethook( nil )
176 _profiler.running = nil
177 end
178
179
180 --
181 -- Simple wrapper to handle the hook. You should not
182 -- be calling this directly. Duplicated to reduce overhead.
183 --
184 function _profiler_hook_wrapper_by_call(action)
185 if _profiler.running == nil then
186 debug.sethook( nil )
187 end
188 _profiler.running:_internal_profile_by_call(action)
189 end
190 function _profiler_hook_wrapper_by_time(action)
191 if _profiler.running == nil then
192 debug.sethook( nil )
193 end
194 _profiler.running:_internal_profile_by_time(action)
195 end
196
197
198 --
199 -- This is the main by-function-call function of the profiler and should not
200 -- be called except by the hook wrapper
201 --
202 function _profiler._internal_profile_by_call(self,action)
203 -- Since we can obtain the 'function' for the item we've had call us, we
204 -- can use that...
205 local caller_info = debug.getinfo( 3 )
206 if caller_info == nil then
207 print "No caller_info"
208 return
209 end
210
211 if caller_info.short_src == "[C]" then
212 -- LMD -- These are builtin functions and for some reason the
213 -- debug hook does not catch the return of these functions.
214 -- So, for now, we are just going to skip them.
215 return
216 end
217
218 --SHG_LOG("[_profiler._internal_profile] "..(caller_info.name or "<nil>"))
219
220 -- Retrieve the most recent activation record...
221 local latest_ar = nil
222 if #self.callstack > 0 then
223 latest_ar = self.callstack[#self.callstack]
224 end
225
226 -- Are we allowed to profile this function?
227 local should_not_profile = 0
228 for k,v in pairs(self.prevented_functions) do
229 if k == caller_info.func then
230 should_not_profile = v
231 end
232 end
233 -- Also check the top activation record...
234 if latest_ar then
235 if latest_ar.should_not_profile == 2 then
236 should_not_profile = 2
237 end
238 end
239
240 -- Now then, are we in 'call' or 'return' ?
241 -- print("Profile:", caller_info.name, "SNP:", should_not_profile,
242 -- "Action:", action )
243 if action == "call" then
244 -- Making a call...
245 local this_ar = {}
246 this_ar.should_not_profile = should_not_profile
247 this_ar.parent_ar = latest_ar
248 this_ar.anon_child = 0
249 this_ar.name_child = 0
250 this_ar.children = {}
251 this_ar.children_time = {}
252 this_ar.clock_start = os.clock()
253 -- Last thing to do on a call is to insert this onto the ar stack...
254 table.insert( self.callstack, this_ar )
255 else
256 local this_ar = latest_ar
257 if this_ar == nil then
258 return -- No point in doing anything if no upper activation record
259 end
260
261 -- Right, calculate the time in this function...
262 this_ar.clock_end = os.clock()
263 this_ar.this_time = this_ar.clock_end - this_ar.clock_start
264
265 -- Now, if we have a parent, update its call info...
266 if this_ar.parent_ar then
267 this_ar.parent_ar.children[caller_info.func] =
268 (this_ar.parent_ar.children[caller_info.func] or 0) + 1
269 this_ar.parent_ar.children_time[caller_info.func] =
270 (this_ar.parent_ar.children_time[caller_info.func] or 0 ) +
271 this_ar.this_time
272 if caller_info.name == nil then
273 this_ar.parent_ar.anon_child =
274 this_ar.parent_ar.anon_child + this_ar.this_time
275 else
276 this_ar.parent_ar.name_child =
277 this_ar.parent_ar.name_child + this_ar.this_time
278 end
279 end
280 -- Now if we're meant to record information about ourselves, do so...
281 if this_ar.should_not_profile == 0 then
282 local inforec = self:_get_func_rec(caller_info.func,1)
283 inforec.count = inforec.count + 1
284 inforec.time = inforec.time + this_ar.this_time
285 inforec.anon_child_time = inforec.anon_child_time + this_ar.anon_child
286 inforec.name_child_time = inforec.name_child_time + this_ar.name_child
287 inforec.func_info = caller_info
288 for k,v in pairs(this_ar.children) do
289 inforec.children[k] = (inforec.children[k] or 0) + v
290 inforec.children_time[k] =
291 (inforec.children_time[k] or 0) + this_ar.children_time[k]
292 end
293 end
294
295 -- Last thing to do on return is to drop the last activation record...
296 table.remove( self.callstack, #self.callstack)
297 end
298 end
299
300
301 --
302 -- This is the main by-time internal function of the profiler and should not
303 -- be called except by the hook wrapper
304 --
305 function _profiler._internal_profile_by_time(self,action)
306 -- we do this first so we add the minimum amount of extra time to this call
307 local timetaken = os.clock() - self.lastclock
308
309 local depth = 3
310 local at_top = true
311 local last_caller
312 local caller = debug.getinfo(depth)
313 while caller do
314 if not caller.func then caller.func = "(tail call)" end
315 if self.prevented_functions[caller.func] == nil then
316 local info = self:_get_func_rec(caller.func, 1, caller)
317 info.count = info.count + 1
318 info.time = info.time + timetaken
319 if last_caller then
320 -- we're not the head, so update the "children" times also
321 if last_caller.name then
322 info.name_child_time = info.name_child_time + timetaken
323 else
324 info.anon_child_time = info.anon_child_time + timetaken
325 end
326 info.children[last_caller.func] =
327 (info.children[last_caller.func] or 0) + 1
328 info.children_time[last_caller.func] =
329 (info.children_time[last_caller.func] or 0) + timetaken
330 end
331 end
332 depth = depth + 1
333 last_caller = caller
334 caller = debug.getinfo(depth)
335 end
336
337 self.lastclock = os.clock()
338 end
339
340
341 --
342 -- This returns a (possibly empty) function record for
343 -- the specified function. It is for internal profiler use.
344 --
345 function _profiler._get_func_rec(self,func,force,info)
346 -- Find the function ref for 'func' (if force and not present, create one)
347 local ret = self.rawstats[func]
348 if ret == nil and force ~= 1 then
349 return nil
350 end
351 if ret == nil then
352 -- Build a new function statistics table
353 ret = {}
354 ret.func = func
355 ret.count = 0
356 ret.time = 0
357 ret.anon_child_time = 0
358 ret.name_child_time = 0
359 ret.children = {}
360 ret.children_time = {}
361 ret.func_info = info
362 self.rawstats[func] = ret
363 end
364 return ret
365 end
366
367
368 --
369 -- This writes a profile report to the output file object. If
370 -- sort_by_total_time is nil or false the output is sorted by
371 -- the function time minus the time in it's children.
372 --
373 function _profiler.report( self, outfile, sort_by_total_time )
374
375 outfile:write
376 [[Lua Profile output created by profiler.lua. Copyright Pepperfish 2002+
377
378 ]]
379
380 -- This is pretty awful.
381 local terms = {}
382 if self.variant == "time" then
383 terms.capitalized = "Sample"
384 terms.single = "sample"
385 terms.pastverb = "sampled"
386 elseif self.variant == "call" then
387 terms.capitalized = "Call"
388 terms.single = "call"
389 terms.pastverb = "called"
390 else
391 assert(false)
392 end
393
394 local total_time = 0
395 local ordering = {}
396 for func,record in pairs(self.rawstats) do
397 table.insert(ordering, func)
398 end
399
400 if sort_by_total_time then
401 table.sort( ordering,
402 function(a,b) return self.rawstats[a].time > self.rawstats[b].time end
403 )
404 else
405 table.sort( ordering,
406 function(a,b)
407 local arec = self.rawstats[a]
408 local brec = self.rawstats[b]
409 local atime = arec.time - (arec.anon_child_time + arec.name_child_time)
410 local btime = brec.time - (brec.anon_child_time + brec.name_child_time)
411 return atime > btime
412 end
413 )
414 end
415
416 for i=1,#ordering do
417 local func = ordering[i]
418 local record = self.rawstats[func]
419 local thisfuncname = " " .. self:_pretty_name(func) .. " "
420 if string.len( thisfuncname ) < 42 then
421 thisfuncname =
422 string.rep( "-", (42 - string.len(thisfuncname))/2 ) .. thisfuncname
423 thisfuncname =
424 thisfuncname .. string.rep( "-", 42 - string.len(thisfuncname) )
425 end
426
427 total_time = total_time + ( record.time - ( record.anon_child_time +
428 record.name_child_time ) )
429 outfile:write( string.rep( "-", 19 ) .. thisfuncname ..
430 string.rep( "-", 19 ) .. "\n" )
431 outfile:write( terms.capitalized.." count: " ..
432 string.format( "%4d", record.count ) .. "\n" )
433 outfile:write( "Time spend total: " ..
434 string.format( "%4.3f", record.time ) .. "s\n" )
435 outfile:write( "Time spent in children: " ..
436 string.format("%4.3f",record.anon_child_time+record.name_child_time) ..
437 "s\n" )
438 local timeinself =
439 record.time - (record.anon_child_time + record.name_child_time)
440 outfile:write( "Time spent in self: " ..
441 string.format("%4.3f", timeinself) .. "s\n" )
442 outfile:write( "Time spent per " .. terms.single .. ": " ..
443 string.format("%4.5f", record.time/record.count) ..
444 "s/" .. terms.single .. "\n" )
445 outfile:write( "Time spent in self per "..terms.single..": " ..
446 string.format( "%4.5f", timeinself/record.count ) .. "s/" ..
447 terms.single.."\n" )
448
449 -- Report on each child in the form
450 -- Child <funcname> called n times and took a.bs
451 local added_blank = 0
452 for k,v in pairs(record.children) do
453 if self.prevented_functions[k] == nil or
454 self.prevented_functions[k] == 0
455 then
456 if added_blank == 0 then
457 outfile:write( "\n" ) -- extra separation line
458 added_blank = 1
459 end
460 outfile:write( "Child " .. self:_pretty_name(k) ..
461 string.rep( " ", 41-string.len(self:_pretty_name(k)) ) .. " " ..
462 terms.pastverb.." " .. string.format("%6d", v) )
463 outfile:write( " times. Took " ..
464 string.format("%4.2f", record.children_time[k] ) .. "s\n" )
465 end
466 end
467
468 outfile:write( "\n" ) -- extra separation line
469 outfile:flush()
470 end
471 outfile:write( "\n\n" )
472 outfile:write( "Total time spent in profiled functions: " ..
473 string.format("%5.3g",total_time) .. "s\n" )
474 outfile:write( [[
475
476 END
477 ]] )
478 outfile:flush()
479 end
480
481
482 --
483 -- This writes the profile to the output file object as
484 -- loadable Lua source.
485 --
486 function _profiler.lua_report(self,outfile)
487 -- Purpose: Write out the entire raw state in a cross-referenceable form.
488 local ordering = {}
489 local functonum = {}
490 for func,record in pairs(self.rawstats) do
491 table.insert(ordering, func)
492 functonum[func] = #ordering
493 end
494
495 outfile:write(
496 "-- Profile generated by profiler.lua Copyright Pepperfish 2002+\n\n" )
497 outfile:write( "-- Function names\nfuncnames = {}\n" )
498 for i=1,#ordering do
499 local thisfunc = ordering[i]
500 outfile:write( "funcnames[" .. i .. "] = " ..
501 string.format("%q", self:_pretty_name(thisfunc)) .. "\n" )
502 end
503 outfile:write( "\n" )
504 outfile:write( "-- Function times\nfunctimes = {}\n" )
505 for i=1,#ordering do
506 local thisfunc = ordering[i]
507 local record = self.rawstats[thisfunc]
508 outfile:write( "functimes[" .. i .. "] = { " )
509 outfile:write( "tot=" .. record.time .. ", " )
510 outfile:write( "achild=" .. record.anon_child_time .. ", " )
511 outfile:write( "nchild=" .. record.name_child_time .. ", " )
512 outfile:write( "count=" .. record.count .. " }\n" )
513 end
514 outfile:write( "\n" )
515 outfile:write( "-- Child links\nchildren = {}\n" )
516 for i=1,#ordering do
517 local thisfunc = ordering[i]
518 local record = self.rawstats[thisfunc]
519 outfile:write( "children[" .. i .. "] = { " )
520 for k,v in pairs(record.children) do
521 if functonum[k] then -- non-recorded functions will be ignored now
522 outfile:write( functonum[k] .. ", " )
523 end
524 end
525 outfile:write( "}\n" )
526 end
527 outfile:write( "\n" )
528 outfile:write( "-- Child call counts\nchildcounts = {}\n" )
529 for i=1,#ordering do
530 local thisfunc = ordering[i]
531 local record = self.rawstats[thisfunc]
532 outfile:write( "children[" .. i .. "] = { " )
533 for k,v in record.children do
534 if functonum[k] then -- non-recorded functions will be ignored now
535 outfile:write( v .. ", " )
536 end
537 end
538 outfile:write( "}\n" )
539 end
540 outfile:write( "\n" )
541 outfile:write( "-- Child call time\nchildtimes = {}\n" )
542 for i=1,#ordering do
543 local thisfunc = ordering[i]
544 local record = self.rawstats[thisfunc];
545 outfile:write( "children[" .. i .. "] = { " )
546 for k,v in pairs(record.children) do
547 if functonum[k] then -- non-recorded functions will be ignored now
548 outfile:write( record.children_time[k] .. ", " )
549 end
550 end
551 outfile:write( "}\n" )
552 end
553 outfile:write( "\n\n-- That is all.\n\n" )
554 outfile:flush()
555 end
556
557 -- Internal function to calculate a pretty name for the profile output
558 function _profiler._pretty_name(self,func)
559
560 -- Only the data collected during the actual
561 -- run seems to be correct.... why?
562 local info = self.rawstats[ func ].func_info
563 -- local info = debug.getinfo( func )
564
565 local name = ""
566 if info.what == "Lua" then
567 name = "L:"
568 end
569 if info.what == "C" then
570 name = "C:"
571 end
572 if info.what == "main" then
573 name = " :"
574 end
575
576 if info.name == nil then
577 name = name .. "<"..tostring(func) .. ">"
578 else
579 name = name .. info.name
580 end
581
582 if info.source then
583 name = name .. "@" .. info.source
584 else
585 if info.what == "C" then
586 name = name .. "@?"
587 else
588 name = name .. "@<string>"
589 end
590 end
591 name = name .. ":"
592 if info.what == "C" then
593 name = name .. "?"
594 else
595 name = name .. info.linedefined
596 end
597
598 return name
599 end
600
601
602 --
603 -- This allows you to specify functions which you do
604 -- not want profiled. Setting level to 1 keeps the
605 -- function from being profiled. Setting level to 2
606 -- keeps both the function and its children from
607 -- being profiled.
608 --
609 -- BUG: 2 will probably act exactly like 1 in "time" mode.
610 -- If anyone cares, let me (zorba) know and it can be fixed.
611 --
612 function _profiler.prevent(self, func, level)
613 self.prevented_functions[func] = (level or 1)
614 end
615
616
617 _profiler.prevented_functions = {
618 [_profiler.start] = 2,
619 [_profiler.stop] = 2,
620 [_profiler._internal_profile_by_time] = 2,
621 [_profiler._internal_profile_by_call] = 2,
622 [_profiler_hook_wrapper_by_time] = 2,
623 [_profiler_hook_wrapper_by_call] = 2,
624 [_profiler.prevent] = 2,
625 [_profiler._get_func_rec] = 2,
626 [_profiler.report] = 2,
627 [_profiler.lua_report] = 2,
628 [_profiler._pretty_name] = 2
629 }