ruen-ui/RuenUI/Benchmark.lua

170 lines
9.7 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

local _, P = ...
-- Read the client's already-running profiler only during /ruen bench.
-- Frame recording is bounded and manual; no scriptProfile or graphics edits.
local fields = {"gxApi", "gxAdapter", "RenderScale", "maxFPS", "maxFPSBk", "vsync",
"useTargetFPS", "graphicsShadowQuality", "graphicsSSAO", "graphicsViewDistance",
"graphicsEnvironmentDetail", "graphicsGroundClutter", "graphicsComputeEffects",
"graphicsLightMode", "graphicsPBRLiquidDetail", "graphicsLiquidDetail", "RAIDsettingsEnabled",
"graphicsParticleDensity", "graphicsSpellDensity", "graphicsProjectedTextures",
"graphicsDepthEffects", "graphicsTextureResolution", "MSAAQuality", "msaaAlphaTest", "ffxAntiAliasingMode"}
local counters = {"CountTimeOver1Ms", "CountTimeOver5Ms", "CountTimeOver10Ms", "CountTimeOver50Ms"}
local function number(fn, ...)
if type(fn) ~= "function" then return end
local ok, value = pcall(fn, ...)
if ok and not (issecretvalue and issecretvalue(value)) and type(value) == "number"
and value == value and value >= 0 and value < math.huge then return value end
end
local function settings()
local result = {}
if C_CVar and C_CVar.GetCVar then
for _, key in ipairs(fields) do result[key] = C_CVar.GetCVar(key) end
end
if GetPhysicalScreenSize then result.width, result.height = GetPhysicalScreenSize() end
local optimizer = RuenUIDB.optimizer
if optimizer then
result.calibrationEnabled = optimizer.enabled
for _, mode in ipairs({"world", "dungeon", "raid", "battleground"}) do
local profile = optimizer.profiles and optimizer.profiles[mode]
if profile then result[mode.."Tier"] = profile.tier; result[mode.."Calibrated"] = profile.calibrated end
end
end
return result
end
local function metric(name)
local api, enum = C_AddOnProfiler, Enum and Enum.AddOnProfilerMetric
if not api or not enum or enum[name] == nil then return end
if api.IsEnabled then
local ok, enabled = pcall(api.IsEnabled)
if not ok or not enabled then return end
end
return number(api.GetAddOnMetric, "RuenUI", enum[name])
end
function P.StartBenchmarkDiagnostics()
local data = {release=P.release, settingsStart=settings(), samples={}, countersStart={}}
for _, name in ipairs(counters) do data.countersStart[name] = metric(name) end
return data
end
function P.SampleBenchmarkDiagnostics(data, fps, worstMS)
if #data.samples >= 180 then return end
local row = {fps=fps, worstFrameMS=worstMS, ruenRecentMS=metric("RecentAverageTime")}
if row.ruenRecentMS ~= nil and C_AddOnProfiler.GetOverallMetric then
row.allAddonsRecentMS = number(C_AddOnProfiler.GetOverallMetric, Enum.AddOnProfilerMetric.RecentAverageTime)
end
-- Keep the relevant neighbors on slow readings, not a scan of every addon.
if (fps < 30 or (worstMS or 0) > 50) and row.ruenRecentMS ~= nil and C_AddOnProfiler.GetTopKAddOnsForMetric then
local ok, top = pcall(C_AddOnProfiler.GetTopKAddOnsForMetric, Enum.AddOnProfilerMetric.RecentAverageTime, 3)
if ok and type(top) == "table" then row.topAddons = top end
end
data.samples[#data.samples+1] = row
end
local frame, capture
local function say(en, ru) print('|cff60d5ffRuen UI:|r '..P.Localized(en,ru or en)) end
function P.IsBenchmarkRunning() return capture ~= nil end
local function finishCapture(partial)
local c=capture
frame:SetScript('OnUpdate',nil); capture=nil
local r=P.FrameSampleSummary(c.sample)
r.time=time(); r.partial=partial or nil; r.diagnostics=c.diagnostics
r.excludedLoadingSeconds=c.excluded; r.focusVerified=false
r.note='Gameplay OnUpdate intervals; 1% low is reciprocal of mean slowest 1% frame time (0.25 ms bins). Loading excluded; window focus unverified.'
local cpuMessage=P.FinishBenchmarkDiagnostics(c.diagnostics)
RuenUIDB.reports=RuenUIDB.reports or {}
table.insert(RuenUIDB.reports,r)
while #RuenUIDB.reports>5 do table.remove(RuenUIDB.reports,1) end
if r.frames>0 then
say(('Frame bench%s: %.1f FPS avg; 1%% low %.1f FPS; p99 %.1f ms; worst %.1f ms. Frames >50/>100/>250 ms: %d/%d/%d over %.1f s.'):format(
partial and ' (partial)' or '',r.meanFPS,r.low1FPS,r.p99MS,r.worstMS,r.over50,r.over100,r.over250,r.seconds),
('Замер кадров%s: среднее %.1f FPS; 1%% low %.1f FPS; p99 %.1f мс; максимум %.1f мс. Кадров >50/>100/>250 мс: %d/%d/%d за %.1f с.'):format(
partial and ' (неполный)' or '',r.meanFPS,r.low1FPS,r.p99MS,r.worstMS,r.over50,r.over100,r.over250,r.seconds))
if r.histogramClipped then say('A stall exceeded 10 seconds: histogram percentiles are capped; worst-frame time is exact.') end
else say('Benchmark stopped without gameplay frames.','Замер остановлен без игровых кадров.') end
say(cpuMessage)
say('Saved on logout/reload. Loading is excluded; app switching is NOT detected. These frame times cannot identify network lag or prove GPU/thermal causes.',
'Сохранится при выходе или /reload. Загрузка исключена; переключение окон НЕ определяется. Замер не устанавливает причину сетевых задержек или перегрева.')
if P.OptimizerBenchmarkEnded then P.OptimizerBenchmarkEnded() end
end
local function update(_,dt)
local c=capture
if not c then return end
if c.paused then return end
if c.loading or c.settle>0 then
c.excluded=c.excluded+dt; c.settle=math.max(0,c.settle-dt); return
end
P.AddFrameSample(c.sample,dt)
c.interval=c.interval+dt; c.worst=math.max(c.worst,dt*1000)
if c.interval>=1 then
P.SampleBenchmarkDiagnostics(c.diagnostics,GetFramerate(),c.worst)
c.interval=0; c.worst=0
end
if c.sample.seconds>=180 then finishCapture() end
end
function P.BenchmarkCommand(arg)
arg=arg or ''
if arg=='status' then
say(capture and ('Benchmark '..(capture.paused and 'paused' or 'running')..': '..math.floor(capture.sample.seconds)..'/180 seconds recorded.') or 'No benchmark running.'); return
elseif arg=='stop' then
if capture then finishCapture(true) else say('No benchmark running.') end; return
elseif arg=='pause' or arg=='resume' then
if not capture then say('No benchmark running.'); return end
capture.paused=arg=='pause'; capture.settle=1
say(capture.paused and 'Benchmark paused.' or 'Benchmark resumed; keep WoW focused.'); return
elseif arg~='' then say('/ruen bench [pause|resume|stop|status]'); return end
if capture then say('A benchmark is already running.'); return end
if P.IsOptimizerCalibrating and P.IsOptimizerCalibrating() then
say('Let optimization finish, or /ruen optimize pause, before benchmarking.',
'Дождитесь окончания настройки или /ruen optimize pause перед замером.'); return
end
if not frame then
frame=CreateFrame('Frame')
frame:RegisterEvent('PLAYER_LEAVING_WORLD'); frame:RegisterEvent('PLAYER_ENTERING_WORLD')
frame:SetScript('OnEvent',function(_,event)
if capture then
capture.loading=event=='PLAYER_LEAVING_WORLD'; capture.settle=2
capture.sample.inHitch=false
end
end)
end
capture={sample=P.NewFrameSample(),diagnostics=P.StartBenchmarkDiagnostics(),interval=0,worst=0,excluded=0,settle=1}
frame:SetScript('OnUpdate',update)
say('Recording every gameplay frame for 3 minutes, including brief hitches. Keep WoW focused; /ruen bench pause before switching apps. No graphics changes.',
'Запись каждого кадра в течение 3 минут, включая короткие рывки. Не переключайте окно; перед переключением /ruen bench pause. Графика не изменяется.')
end
function P.FinishBenchmarkDiagnostics(data)
data.settingsEnd = settings()
data.settingsChanged = false
for key, value in pairs(data.settingsStart) do
if data.settingsEnd[key] ~= value then data.settingsChanged = true end
end
for key, value in pairs(data.settingsEnd) do
if data.settingsStart[key] ~= value then data.settingsChanged = true end
end
local total, count, maximum = 0, 0, 0
for _, row in ipairs(data.samples) do
if row.ruenRecentMS ~= nil then
total=total+row.ruenRecentMS; count=count+1; maximum=math.max(maximum,row.ruenRecentMS)
end
end
if count > 0 then data.sampledMeanMS=total/count; data.maxSampledRecentMS=maximum end
data.ticksOver = {}
for _, name in ipairs(counters) do
local before, after = data.countersStart[name], metric(name)
if before ~= nil and after ~= nil and after >= before then data.ticksOver[name] = after-before end
end
data.note = "Native recent metrics average the last 60 ticks; sampled about once/second. Threshold deltas cover this run's wall time (including pause/loading), not the whole login. Slow-frame correlation is not proof of causation."
local message
if data.sampledMeanMS then
local slow = data.ticksOver.CountTimeOver5Ms
message = string.format("Ruen CPU: sampled mean %.3f ms/tick; largest sampled recent average %.3f ms; ticks over 5 ms: %s.",
data.sampledMeanMS, data.maxSampledRecentMS, slow ~= nil and tostring(slow) or "unavailable")
else message = "Ruen CPU timing unavailable on this client; FPS alone cannot identify addon cost." end
if data.settingsChanged then message = message.." Graphics/calibration settings changed during this sample; comparison is inconclusive." end
return message
end