local LuaHookUtil = {} local _hookFuncData = {} local function FunctionHook(action) if action == 'call' then local info = debug.getinfo(2, 'f') local func = info.func local tracker = _hookFuncData[func] if tracker then local stack = debug.traceback('', 3) local calls = tracker.calls local count = calls[stack] if count then calls[stack] = count + 1 else calls[stack] = 1 end end end end function LuaHookUtil.RegistHookFunc(funcName, hookFunc) local info = debug.getinfo(hookFunc) _hookFuncData[hookFunc] = {funcName = funcName, funcSummary = funcName..info.source..':'..info.linedefined, calls = {}} end local function PrintSummary(minCount) minCount = minCount or 0 local sorted = {} for func, tracker in pairs(_hookFuncData) do local funcName = tracker.funcName local funcSummary = tracker.funcSummary local calls = tracker.calls for stack, count in pairs(calls) do if count > minCount then table.insert(sorted, {funcName = funcName, funcSummary = funcSummary, call_count = count, stack = stack}) end end end table.sort(sorted, function(a, b) if a.funcName == b.funcName then if a.call_count == b.call_count then return a.stack < b.stack else return a.call_count < b.call_count end else return a.funcName < b.funcName end end) for _, item in ipairs(sorted) do print(item.funcSummary, string.format('calls %d', item.call_count), item.stack) end end function LuaHookUtil.ToggleHook() local isOn = debug.gethook() if isOn then debug.sethook(nil) else debug.sethook(FunctionHook, 'c') end end local FuncExcuteData = {} function LuaHookUtil.AddOneFuncExcuteTime(beforeTime, func) local funcTime = AuxUtil.GetLocalTimeStampMS()-beforeTime if funcTime == 0 then return end local funcInfo = debug.getinfo(func) local dataKey = funcInfo.source..':'..funcInfo.linedefined if not FuncExcuteData[dataKey] or funcTime>FuncExcuteData[dataKey] then FuncExcuteData[dataKey] = funcTime end end function LuaHookUtil.PrintFuncExcuteData() local printStr = "方法信息,执行时间\n" for dataKey, time in pairs(FuncExcuteData) do printStr = printStr..dataKey..","..time.."\n" end LuaExt.FileWriteText("FuncExcuteData.csv", printStr) end --统计某一个函数的运行时间 --在函数运行前获取当前的时间,精确到毫秒,可以用AuxUtil.GetLocalTimeStampMS() --函数运行结束后,调用LuaHookUtil.AddOneFuncExcuteTime方法 --LuaHookUtil.PrintFuncExcuteData 将所有的函数运行时间输出到一个csv文件中,放到工程的目录 return LuaHookUtil