profiler.lua 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. local reports = {}
  2. local LuaProfiler = {}
  3. function LuaProfiler.formatFuncInfo(funcinfo)
  4. local name = funcinfo.name or 'unknown'
  5. local line = funcinfo.linedefined or 0
  6. local source = funcinfo.short_src or 'unknown'
  7. local key = string.format("%s|%s|%s", name, source, line)
  8. local result = {
  9. name= name,
  10. line= line,
  11. source= source,
  12. key= key
  13. }
  14. return result
  15. end
  16. function LuaProfiler.tracingCall(funcinfo)
  17. local info = LuaProfiler.formatFuncInfo(funcinfo)
  18. local key = info.key
  19. if not reports[key] then
  20. reports[key] = {
  21. callcount = 0,
  22. totaltime = 0,
  23. }
  24. end
  25. local report = reports[key]
  26. report.calltime = os.clock()
  27. report.callcount = report.callcount + 1
  28. report.name = info.name
  29. report.source = info.source
  30. report.line = info.line
  31. end
  32. function LuaProfiler.tracingReturn(funcinfo)
  33. local info = LuaProfiler.formatFuncInfo(funcinfo)
  34. local key = info.key
  35. local stoptime = os.clock()
  36. local report = reports[key]
  37. if report and report.calltime and report.calltime > 0 then
  38. report.totaltime = report.totaltime + (stoptime-report.calltime)
  39. report.calltime = 0
  40. end
  41. end
  42. function LuaProfiler.tracingHandler(hooktype)
  43. local funcinfo = debug.getinfo(2, 'nS')
  44. if hooktype == "call" then
  45. LuaProfiler.tracingCall(funcinfo)
  46. elseif hooktype == "return" then
  47. LuaProfiler.tracingReturn(funcinfo)
  48. end
  49. end
  50. function luaprofilercollect()
  51. if table.isNullOrEmpty(reports) then
  52. return nil
  53. end
  54. local result = table.values(reports)
  55. --被获取后清空
  56. reports = {}
  57. return result
  58. end
  59. function luainit()
  60. if is_open_break_point_debug() then
  61. --打开断点调试器,延迟5秒执行
  62. setontimerex(TimerIds.OPEN_BREAK_POINT_DEBUG, 9999999, 5)
  63. end
  64. -- local isDebug = getenv("debug")
  65. -- if isDebug then
  66. -- debug.sethook(LuaProfiler.tracingHandler, 'cr', 0)
  67. -- end
  68. end
  69. function ontimerex100006()
  70. local lpd = require("LuaPanda")
  71. lpd.start("127.0.0.1", 8818)
  72. lpd.autoReconnect = true
  73. info("断点调试器打开")
  74. setofftimerex(TimerIds.OPEN_BREAK_POINT_DEBUG)
  75. end
  76. function is_open_break_point_debug()
  77. local luaversion = getenv("luaversion")
  78. local isdbg = getenv("debug");
  79. local ok = isdbg == true and string.lower(luaversion) == "luacdbg"
  80. return ok
  81. end