profiler.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. local isDebug = getenv("debug")
  61. if isDebug then
  62. debug.sethook(LuaProfiler.tracingHandler, 'cr', 0)
  63. end
  64. end