-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddonProfiler.lua
1888 lines (1684 loc) · 75.9 KB
/
AddonProfiler.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local thisAddonName = ...
local s_trim = string.trim
local t_insert = table.insert
local t_removemulti = table.removemulti
local t_wipe = table.wipe
local pairs = pairs
local GetTime = GetTime
local C_AddOnProfiler_GetAddOnMetric = C_AddOnProfiler.GetAddOnMetric;
local C_AddOnProfiler_GetOverallMetric = C_AddOnProfiler.GetOverallMetric;
local Enum_AddOnProfilerMetric_LastTime = Enum.AddOnProfilerMetric.LastTime;
local Enum_AddOnProfilerMetric_RecentAverageTime = Enum.AddOnProfilerMetric.RecentAverageTime;
local Enum_AddOnProfilerMetric_EncounterAverageTime = Enum.AddOnProfilerMetric.EncounterAverageTime;
local Enum_AddOnProfilerMetric_PeakTime = Enum.AddOnProfilerMetric.PeakTime;
local NAP = {};
NAP.eventFrame = CreateFrame('Frame');
_G.NumyAddonProfiler = NAP;
local msOptions = {1, 5, 10, 50, 100, 500, 1000};
-- the metrics that can be fake reset, since they're just incremental
local resettableMetrics = {
[Enum.AddOnProfilerMetric.CountTimeOver1Ms] = 1,
[Enum.AddOnProfilerMetric.CountTimeOver5Ms] = 5,
[Enum.AddOnProfilerMetric.CountTimeOver10Ms] = 10,
[Enum.AddOnProfilerMetric.CountTimeOver50Ms] = 50,
[Enum.AddOnProfilerMetric.CountTimeOver100Ms] = 100,
[Enum.AddOnProfilerMetric.CountTimeOver500Ms] = 500,
[Enum.AddOnProfilerMetric.CountTimeOver1000Ms] = 1000,
};
local msMetricMap = {
[1] = Enum.AddOnProfilerMetric.CountTimeOver1Ms,
[5] = Enum.AddOnProfilerMetric.CountTimeOver5Ms,
[10] = Enum.AddOnProfilerMetric.CountTimeOver10Ms,
[50] = Enum.AddOnProfilerMetric.CountTimeOver50Ms,
[100] = Enum.AddOnProfilerMetric.CountTimeOver100Ms,
[500] = Enum.AddOnProfilerMetric.CountTimeOver500Ms,
[1000] = Enum.AddOnProfilerMetric.CountTimeOver1000Ms,
};
local msOptionFieldMap = {};
for ms in pairs(msMetricMap) do
msOptionFieldMap[ms] = "over" .. ms .. "Ms";
end
local TOTAL_ADDON_METRICS_KEY = "\00total\00";
local HISTORY_TYPE_SINCE_RESET = 'sinceReset';
local HISTORY_TYPE_COMBAT = 'combat';
local HISTORY_TYPE_ENCOUNTER = 'encounter';
local HISTORY_TYPE_TIME_RANGE = 'timeRange';
local HISTORY_LATEST = -1;
local HISTORY_TIME_RANGES = {5, 15, 30, 60, 120, 300, 600} -- 5sec - 10min
NAP.currentHistorySelection = {
type = HISTORY_TYPE_TIME_RANGE,
timeRange = 30,
encounterIndex = HISTORY_LATEST,
combatIndex = HISTORY_LATEST,
};
--- @type table<string, table<string, number>> [addonName] = { [metricName] = value }
NAP.resetBaselineMetrics = {};
NAP.totalMs = { [TOTAL_ADDON_METRICS_KEY] = 0 };
NAP.loadedAtTick = { [TOTAL_ADDON_METRICS_KEY] = 0 };
NAP.tickNumber = 0;
NAP.peakMs = { [TOTAL_ADDON_METRICS_KEY] = 0 };
NAP.combatPeakMs = nil;
NAP.encounterPeakMs = nil;
NAP.snapshots = {
--- @type NAP_Bucket[]
buckets = {},
--- @type NAP_Bucket # reference to the latest bucket
lastBucket = nil,
};
do
--- @type NAP_Bucket
local lastBucket = {
tickMap = {},
lastTick = {},
curTickIndex = 0;
};
NAP.snapshots.buckets[1] = lastBucket;
NAP.snapshots.lastBucket = lastBucket;
end
--- @type NAP_EncounterSnapshot[]
NAP.encounterSnapshots = {};
--- @type NAP_CombatSnapshot[]
NAP.combatSnapshots = {};
--- collect all available data
local MODE_ACTIVE = 'active';
--- collect only total and peak data - disables history range
local MODE_PERFORMANCE = 'performance';
--- collect no data at all, just reset the spike ms counters on reset - disables history range, and maybe show different columns?
local MODE_PASSIVE = 'passive';
--- @type table<string, NAP_AddonInfo>
NAP.addons = {};
--- @type table<string, boolean> # list of addon names
NAP.loadedAddons = {};
--- Note: NAP:Init() is called at the end of the script body, BEFORE the addon_loaded event
function NAP:Init()
for i = 1, C_AddOns.GetNumAddOns() do
local addonName, title, notes = C_AddOns.GetAddOnInfo(i);
local isLoaded = C_AddOns.IsAddOnLoaded(addonName);
if title == '' then
title = addonName;
end
local version = C_AddOns.GetAddOnMetadata(addonName, 'Version');
if version and version ~= '' then
title = title .. ' |cff808080(' .. version .. ')|r';
end
self.addons[addonName] = {
title = title,
notes = notes,
};
if isLoaded and addonName ~= thisAddonName then
self:ADDON_LOADED(addonName);
end
end
self.eventFrame:SetScript('OnEvent', function(_, event, ...)
if self[event] then self[event](self, ...); end
end);
self.eventFrame:RegisterEvent('ADDON_LOADED');
self.eventFrame:RegisterEvent('ENCOUNTER_START');
self.eventFrame:RegisterEvent('ENCOUNTER_END');
self.eventFrame:RegisterEvent('PLAYER_REGEN_DISABLED');
self.eventFrame:RegisterEvent('PLAYER_REGEN_ENABLED');
self.collectData = true;
self:StartPurgeTicker();
SLASH_NUMY_ADDON_PROFILER1 = '/nap';
SLASH_NUMY_ADDON_PROFILER2 = '/addonprofile';
SLASH_NUMY_ADDON_PROFILER3 = '/addonprofiler';
SLASH_NUMY_ADDON_PROFILER4 = '/addoncpu';
SlashCmdList['NUMY_ADDON_PROFILER'] = function(message)
if message == 'reset' then
wipe(self.db.minimap);
self.db.minimap.hide = false;
local name = 'NumyAddonProfiler';
LibStub('LibDBIcon-1.0'):Hide(name);
LibStub('LibDBIcon-1.0'):Show(name);
return;
end
self:ToggleFrame();
end;
RunNextFrame(function()
if NumyProfiler then -- the irony of profiling the profiler (-:
self.OnUpdateActiveMode = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'OnUpdateActiveMode', self.OnUpdateActiveMode);
self.OnUpdatePerformanceMode = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'OnUpdatePerformanceMode', self.OnUpdatePerformanceMode);
self.PurgeOldData = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'PurgeOldData', self.PurgeOldData);
self.ENCOUNTER_START = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'ENCOUNTER_START', self.ENCOUNTER_START);
self.ENCOUNTER_END = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'ENCOUNTER_END', self.ENCOUNTER_END);
self.PLAYER_REGEN_DISABLED = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'PLAYER_REGEN_DISABLED', self.PLAYER_REGEN_DISABLED);
self.PLAYER_REGEN_ENABLED = NumyProfiler:Wrap(thisAddonName, 'ProfilerCore', 'PLAYER_REGEN_ENABLED', self.PLAYER_REGEN_ENABLED);
end
self:SwitchMode(self.db.mode, true);
end);
end
local HEADER_IDS = {
addonTitle = "addonTitle",
encounterAvgMs = "encounterAvgMs",
overallEncounterAvgPercent = "overallEncounterAvgPercent",
peakTimeMs = "peakTimeMs",
overallPeakTimePercent = "overallPeakTimePercent",
recentMs = "recentMs",
overallRecentPercent = "overallRecentPercent",
averageMs = "averageMs",
totalMs = "totalMs",
overallTotalPercent = "overallTotalPercent",
applicationTotalPercent = "applicationTotalPercent",
["overCount-1"] = "overCount-1",
["overCount-5"] = "overCount-5",
["overCount-10"] = "overCount-10",
["overCount-50"] = "overCount-50",
["overCount-100"] = "overCount-100",
["overCount-500"] = "overCount-500",
["overCount-1000"] = "overCount-1000",
spikeSumMs = "spikeSumMs",
}
function NAP:InitDB()
if not AddonProfilerDB then
AddonProfilerDB = {};
end
self.db = AddonProfilerDB;
local defaultShownColumns = {
[HEADER_IDS.addonTitle] = true,
[HEADER_IDS.encounterAvgMs] = true,
[HEADER_IDS.overallEncounterAvgPercent] = false,
[HEADER_IDS.peakTimeMs] = true,
[HEADER_IDS.overallPeakTimePercent] = false,
[HEADER_IDS.recentMs] = false,
[HEADER_IDS.overallRecentPercent] = false,
[HEADER_IDS.averageMs] = true,
[HEADER_IDS.totalMs] = true,
[HEADER_IDS.overallTotalPercent] = true,
[HEADER_IDS.applicationTotalPercent] = true,
[HEADER_IDS['overCount-1']] = true,
[HEADER_IDS['overCount-5']] = true,
[HEADER_IDS['overCount-10']] = true,
[HEADER_IDS['overCount-50']] = true,
[HEADER_IDS['overCount-100']] = true,
[HEADER_IDS['overCount-500']] = true,
[HEADER_IDS['overCount-1000']] = true,
[HEADER_IDS.spikeSumMs] = true,
};
self.db.shownColumns = self.db.shownColumns or {};
for columnID, shown in pairs(defaultShownColumns) do
if self.db.shownColumns[columnID] == nil then
self.db.shownColumns[columnID] = shown;
end
end
self.db.mode = self.db.mode or MODE_ACTIVE;
self.db.minimap = self.db.minimap or {};
self.db.minimap.hide = self.db.minimap.hide or false;
end
function NAP:ADDON_LOADED(addonName)
if thisAddonName == addonName then
self:InitDB();
AddonProfilerDB = AddonProfilerDB or {};
self.db = AddonProfilerDB;
self:InitUI();
self:InitMinimapButton();
end
if 'BlizzMove' == addonName then
self:RegisterIntoBlizzMove();
end
if not self.addons[addonName] then return end
self.loadedAddons[addonName] = true;
self.totalMs[addonName] = 0;
self.loadedAtTick[addonName] = self.tickNumber;
self.peakMs[addonName] = 0;
self.snapshots.lastBucket.lastTick[addonName] = {};
self.resetBaselineMetrics[addonName] = self:GetCurrentMsSpikeMetrics(addonName);
end
function NAP:SwitchMode(newMode, force)
if newMode == self.db.mode and not force then
return;
end
self.db.mode = newMode;
if newMode == MODE_ACTIVE then
self.eventFrame:SetScript('OnUpdate', function() self:OnUpdateActiveMode() end);
elseif newMode == MODE_PERFORMANCE then
self.eventFrame:SetScript('OnUpdate', function() self:OnUpdatePerformanceMode() end);
elseif newMode == MODE_PASSIVE then
self.eventFrame:SetScript('OnUpdate', nil);
end
self:ResetMetrics();
self.ProfilerFrame:RefreshActiveColumns();
self.ProfilerFrame:UpdateHeaders();
RunNextFrame(function()
self.ProfilerFrame.Headers:UpdateArrow();
self.ProfilerFrame:UpdateSortComparator();
if self.ProfilerFrame:IsShown() then
self.ProfilerFrame:DoUpdate(true);
end
end);
end
function NAP:OnUpdateActiveMode()
self.tickNumber = self.tickNumber + 1;
local lastBucket = self.snapshots.lastBucket;
local curTickIndex = lastBucket.curTickIndex + 1;
lastBucket.curTickIndex = curTickIndex;
lastBucket.tickMap[curTickIndex] = GetTime();
local lastTick = lastBucket.lastTick;
local totalMs = self.totalMs;
local peakMs = self.peakMs;
local overallLastTickMs = C_AddOnProfiler_GetOverallMetric(Enum_AddOnProfilerMetric_LastTime);
if overallLastTickMs > 0 then
totalMs[TOTAL_ADDON_METRICS_KEY] = totalMs[TOTAL_ADDON_METRICS_KEY] + overallLastTickMs;
lastTick[TOTAL_ADDON_METRICS_KEY][curTickIndex] = overallLastTickMs;
if overallLastTickMs > peakMs[TOTAL_ADDON_METRICS_KEY] then
peakMs[TOTAL_ADDON_METRICS_KEY] = overallLastTickMs;
end
end
for addonName in pairs(self.loadedAddons) do
local lastTickMs = C_AddOnProfiler_GetAddOnMetric(addonName, Enum_AddOnProfilerMetric_LastTime);
if lastTickMs > 0 then
totalMs[addonName] = totalMs[addonName] + lastTickMs;
lastTick[addonName][curTickIndex] = lastTickMs;
if lastTickMs > peakMs[addonName] then
peakMs[addonName] = lastTickMs;
end
end
end
end
--- performance mode OnUpdate script
--- right now the only difference is that it doesn't store the lastTickMs
--- more differences might come up in the future
function NAP:OnUpdatePerformanceMode()
self.tickNumber = self.tickNumber + 1;
local totalMs = self.totalMs;
local peakMs = self.peakMs;
local combatPeakMs = self.combatPeakMs;
local encounterPeakMs = self.encounterPeakMs;
local overallLastTickMs = C_AddOnProfiler_GetOverallMetric(Enum_AddOnProfilerMetric_LastTime);
if overallLastTickMs > 0 then
totalMs[TOTAL_ADDON_METRICS_KEY] = totalMs[TOTAL_ADDON_METRICS_KEY] + overallLastTickMs;
if overallLastTickMs > peakMs[TOTAL_ADDON_METRICS_KEY] then
peakMs[TOTAL_ADDON_METRICS_KEY] = overallLastTickMs;
end
if combatPeakMs and overallLastTickMs > (combatPeakMs[TOTAL_ADDON_METRICS_KEY] or 0) then
combatPeakMs[TOTAL_ADDON_METRICS_KEY] = overallLastTickMs;
end
if encounterPeakMs and overallLastTickMs > (encounterPeakMs[TOTAL_ADDON_METRICS_KEY] or 0) then
encounterPeakMs[TOTAL_ADDON_METRICS_KEY] = overallLastTickMs;
end
end
for addonName in pairs(self.loadedAddons) do
local lastTickMs = C_AddOnProfiler_GetAddOnMetric(addonName, Enum_AddOnProfilerMetric_LastTime);
if lastTickMs > 0 then
totalMs[addonName] = totalMs[addonName] + lastTickMs;
if lastTickMs > peakMs[addonName] then
peakMs[addonName] = lastTickMs;
end
if combatPeakMs and lastTickMs > (combatPeakMs[addonName] or 0) then
combatPeakMs[addonName] = lastTickMs;
end
if encounterPeakMs and lastTickMs > (encounterPeakMs[addonName] or 0) then
encounterPeakMs[addonName] = lastTickMs;
end
end
end
end
function NAP:InitNewBucket()
local lastBucket = { curTickIndex = 0, tickMap = {}, lastTick = { [TOTAL_ADDON_METRICS_KEY] = {} } };
for addonName in pairs(self.loadedAddons) do
lastBucket.lastTick[addonName] = {};
end
t_insert(self.snapshots.buckets, lastBucket);
self.snapshots.lastBucket = lastBucket;
return lastBucket;
end
local BUCKET_CUTOFF = 2000; -- rather arbitrary number, but interestingly, the lower your fps, the less often actual work will be performed to purge old data ^^
function NAP:PurgeOldData()
if self.db.mode ~= MODE_ACTIVE then -- only active mode uses buckets
return;
end
if self.snapshots.lastBucket.curTickIndex > BUCKET_CUTOFF then
self:InitNewBucket();
end
local buckets = self.snapshots.buckets
local firstBucket = buckets[1];
if not buckets[2] or not firstBucket.tickMap[1] then
return;
end
local timestamp = GetTime();
local cutoff = timestamp - HISTORY_TIME_RANGES[#HISTORY_TIME_RANGES];
if firstBucket.tickMap[1] > cutoff then
return;
end
local to;
for i, bucket in ipairs(buckets) do
if bucket.tickMap[1] and bucket.tickMap[1] > cutoff then
to = i - 1;
break;
end
end
if to and to > 1 then
t_removemulti(buckets, 1, to);
end
end
function NAP:PLAYER_REGEN_DISABLED()
self:StopPurgeTicker();
if self.db.mode == MODE_PERFORMANCE then
self.combatPeakMs = { [TOTAL_ADDON_METRICS_KEY] = 0 };
end
self.combatSnapshots = {
{ -- might add a list of combat snapshots in the future, for now it's just 1
snapshot = self:InitNewSnapshot(self.combatPeakMs),
},
};
end
function NAP:PLAYER_REGEN_ENABLED()
self:StartPurgeTicker();
local snapshot = self.combatSnapshots[#self.combatSnapshots];
if not snapshot then
print('NumyAddonProfiler: combat ended without matching combat start');
return;
end
self:CloseSnapshot(snapshot.snapshot);
self.combatPeakMs = nil
end
function NAP:ENCOUNTER_START(encounterID, encounterName, difficultyID, _)
if (select(2, GetDifficultyInfo(difficultyID)) ~= 'raid') then return; end
if self.db.mode == MODE_PERFORMANCE then
self.encounterPeakMs = { [TOTAL_ADDON_METRICS_KEY] = 0 };
end
local snapshot = {
encounterID = encounterID,
name = encounterName,
snapshot = self:InitNewSnapshot(self.encounterPeakMs),
};
t_insert(self.encounterSnapshots, snapshot);
end
function NAP:ENCOUNTER_END(encounterID, _, difficultyID, _, success)
if (select(2, GetDifficultyInfo(difficultyID)) ~= 'raid') then return; end
local snapshot = self.encounterSnapshots[#self.encounterSnapshots];
if not snapshot or snapshot.encounterID ~= encounterID then
print('NumyAddonProfiler: encounter ended without matching encounter start');
return;
end
snapshot.kill = success == 1;
self:CloseSnapshot(snapshot.snapshot);
self.encounterPeakMs = nil;
end
function NAP:StartPurgeTicker()
if self.purgerTicker then
self.purgerTicker:Cancel()
end
-- continiously purge older entires
self.purgerTicker = C_Timer.NewTicker(5, function() self:PurgeOldData() end)
end
function NAP:StopPurgeTicker()
if self.purgerTicker then
self.purgerTicker:Cancel()
self.purgerTicker = nil
end
end
function NAP:ResetMetrics()
self.resetBaselineMetrics = self:GetCurrentMsSpikeMetrics();
self.tickNumber = 0;
self.resetTime = GetTime();
self.snapshots.buckets = {};
self:InitNewBucket();
for addonName in pairs(self.loadedAddons) do
self.totalMs[addonName] = 0;
self.peakMs[addonName] = 0;
self.loadedAtTick[addonName] = 0;
end
self.totalMs[TOTAL_ADDON_METRICS_KEY] = 0;
self.peakMs[TOTAL_ADDON_METRICS_KEY] = 0;
end
--- @param peakMsTable nil|table<string, number>
--- @return NAP_PartialSnapshot
function NAP:InitNewSnapshot(peakMsTable)
return {
startMetrics = self:GetCurrentMsSpikeMetrics(),
startTime = GetTime(),
startTick = self.tickNumber,
startTotal = self.db.mode ~= MODE_PASSIVE and CopyTable(self.totalMs) or {},
peakTime = peakMsTable,
bucketStartTick = self.snapshots.lastBucket.curTickIndex,
isComplete = false,
};
end
--- @param snapshot NAP_PartialSnapshot
function NAP:CloseSnapshot(snapshot)
--- @type NAP_Snapshot
snapshot = snapshot; ---@diagnostic disable-line: assign-type-mismatch
snapshot.endMetrics = self:GetCurrentMsSpikeMetrics();
snapshot.endTime = GetTime();
snapshot.endTick = self.tickNumber;
snapshot.bossAvg = self:GetCurrentMetrics(Enum_AddOnProfilerMetric_EncounterAverageTime);
snapshot.recentAvg = self:GetCurrentMetrics(Enum_AddOnProfilerMetric_RecentAverageTime);
if self.db.mode ~= MODE_PASSIVE then
snapshot.total = {};
for addonName, endTotal in pairs(self.totalMs) do
snapshot.total[addonName] = endTotal - (snapshot.startTotal[addonName] or 0);
end
end
snapshot.startTotal = nil;
if self.db.mode == MODE_ACTIVE then
snapshot.peakTime = {};
local bucket = {
lastTick = {},
tickMap = {},
curTickIndex = 0,
};
local lastBucket = self.snapshots.lastBucket;
for index = snapshot.bucketStartTick, lastBucket.curTickIndex do
local tickIndex = bucket.curTickIndex + 1;
bucket.curTickIndex = tickIndex;
bucket.tickMap[tickIndex] = lastBucket.tickMap[index];
end
for addonName, lastTicks in pairs(lastBucket.lastTick) do
snapshot.peakTime[addonName] = 0;
local newTicks = {};
local tickIndex = 0;
for index = snapshot.bucketStartTick, lastBucket.curTickIndex do
tickIndex = tickIndex + 1;
local lastTick = lastTicks[index];
if lastTick then
newTicks[tickIndex] = lastTicks[index];
if lastTicks[index] > snapshot.peakTime[addonName] then
snapshot.peakTime[addonName] = lastTicks[index];
end
end
end
bucket.lastTick[addonName] = newTicks;
end
snapshot.bucket = bucket;
else
snapshot.peakTime = snapshot.peakTime or self:GetCurrentMetrics(Enum_AddOnProfilerMetric_PeakTime);
end
snapshot.isComplete = true;
end
function NAP:GetCurrentMsSpikeMetrics(onlyForAddonName)
local currentMetrics = {};
if not onlyForAddonName then
currentMetrics[TOTAL_ADDON_METRICS_KEY] = {};
for metric, ms in pairs(resettableMetrics) do
currentMetrics[TOTAL_ADDON_METRICS_KEY][ms] = C_AddOnProfiler_GetOverallMetric(metric);
end
for addonName in pairs(self.loadedAddons) do
currentMetrics[addonName] = {};
for metric, ms in pairs(resettableMetrics) do
currentMetrics[addonName][ms] = C_AddOnProfiler_GetAddOnMetric(addonName, metric);
end
end
else
if TOTAL_ADDON_METRICS_KEY == onlyForAddonName then
for metric, ms in pairs(resettableMetrics) do
currentMetrics[ms] = C_AddOnProfiler_GetOverallMetric(metric);
end
else
for metric, ms in pairs(resettableMetrics) do
currentMetrics[ms] = C_AddOnProfiler_GetAddOnMetric(onlyForAddonName, metric);
end
end
end
return currentMetrics;
end
--- @param metric any # Enum.AddOnProfilerMetric
--- @return table<string, number> # addonName -> metricValue
function NAP:GetCurrentMetrics(metric)
local currentMetrics = {};
currentMetrics[TOTAL_ADDON_METRICS_KEY] = C_AddOnProfiler_GetOverallMetric(metric);
for addonName in pairs(self.loadedAddons) do
currentMetrics[addonName] = C_AddOnProfiler_GetAddOnMetric(addonName, metric);
end
return currentMetrics;
end
--- @return string historyType
--- @return number|nil historyIndex # combatIndex, encounterIndex, or timeRange
function NAP:GetActiveHistoryRange()
local type = self.currentHistorySelection.type;
if HISTORY_TYPE_TIME_RANGE == type and self.db.mode ~= MODE_ACTIVE then
type = HISTORY_TYPE_SINCE_RESET;
end
if HISTORY_TYPE_SINCE_RESET == type then
return HISTORY_TYPE_SINCE_RESET, nil;
elseif HISTORY_TYPE_COMBAT == type then
return HISTORY_TYPE_COMBAT, self.currentHistorySelection.combatIndex;
elseif HISTORY_TYPE_ENCOUNTER == type then
return HISTORY_TYPE_ENCOUNTER, self.currentHistorySelection.encounterIndex;
end
-- if something went wrong, default to time range
return HISTORY_TYPE_TIME_RANGE, self.currentHistorySelection.timeRange;
end
--- @param forceUpdate boolean
--- @return table<NAP_Bucket, number>? bucketsWithinHistory
function NAP:PrepareFilteredData(forceUpdate)
local now = self.frozenAt or GetTime();
local historyType, historyIndex = self:GetActiveHistoryRange();
local timestampOffset = 0;
if historyType == HISTORY_TYPE_TIME_RANGE and historyIndex then
timestampOffset = historyIndex;
end
local minTimestamp = now - timestampOffset;
local prevTimestamp = self.minTimeStamp;
local prevMatch = self.prevMatch;
local prevHistoryType = self.prevHistoryType;
local prevHistoryIndex = self.prevHistoryIndex;
if
not forceUpdate
and prevTimestamp == minTimestamp
and prevMatch == self.curMatch
and prevHistoryType == historyType
and prevHistoryIndex == historyIndex
then
return nil;
end
t_wipe(self.filteredData);
self.dataProvider = nil;
self.minTimeStamp = minTimestamp;
self.prevMatch = self.curMatch;
self.prevHistoryType = historyType;
self.prevHistoryIndex = historyIndex;
local withinHistory = {};
if HISTORY_TYPE_TIME_RANGE == historyType then
for _, bucket in ipairs(self.snapshots.buckets) do
if bucket.tickMap and bucket.tickMap[bucket.curTickIndex] and bucket.tickMap[bucket.curTickIndex] > minTimestamp then
for tickIndex, timestamp in pairs(bucket.tickMap) do
if timestamp > minTimestamp then
withinHistory[bucket] = tickIndex;
break;
end
end
end
end
end
local snapshot = nil;
if HISTORY_TYPE_COMBAT == historyType then
local index = historyIndex;
if index == HISTORY_LATEST then
index = #self.combatSnapshots;
end
snapshot = self.combatSnapshots[index] and self.combatSnapshots[index].snapshot;
elseif HISTORY_TYPE_ENCOUNTER == historyType then
local index = historyIndex;
if index == HISTORY_LATEST then
index = #self.encounterSnapshots;
end
snapshot = self.encounterSnapshots[index] and self.encounterSnapshots[index].snapshot;
end
if snapshot and not snapshot.isComplete then
snapshot = nil;
end
if snapshot and snapshot.bucket then
withinHistory[snapshot.bucket] = 1;
end
local overallSnapshotOverrides;
if snapshot then
overallSnapshotOverrides = {
encounterAvg = snapshot.bossAvg[TOTAL_ADDON_METRICS_KEY] or 0,
recentMs = snapshot.recentAvg[TOTAL_ADDON_METRICS_KEY] or 0,
peakTime = snapshot.peakTime[TOTAL_ADDON_METRICS_KEY] or 0,
totalMs = snapshot.total[TOTAL_ADDON_METRICS_KEY] or 0,
numberOfTicks = snapshot.endTick - snapshot.startTick,
applicationTotalMs = (snapshot.endTime - snapshot.startTime) * 1000,
startMetrics = snapshot.startMetrics[TOTAL_ADDON_METRICS_KEY] or {},
endMetrics = snapshot.endMetrics[TOTAL_ADDON_METRICS_KEY] or {},
};
end
local overallStats = self:GetElelementDataForAddon(TOTAL_ADDON_METRICS_KEY, nil, withinHistory, nil, overallSnapshotOverrides);
for addonName in pairs(self.loadedAddons) do
local info = self.addons[addonName];
if info.title:lower():match(self.curMatch) then
local snapshotOverrides;
if snapshot then
snapshotOverrides = {
encounterAvg = snapshot.bossAvg[addonName] or 0,
recentMs = snapshot.recentAvg[addonName] or 0,
peakTime = snapshot.peakTime[addonName] or 0,
totalMs = snapshot.total[addonName] or 0,
numberOfTicks = overallSnapshotOverrides and overallSnapshotOverrides.numberOfTicks or 0,
applicationTotalMs = overallSnapshotOverrides and overallSnapshotOverrides.applicationTotalMs or 0,
startMetrics = snapshot.startMetrics[addonName] or {},
endMetrics = snapshot.endMetrics[addonName] or {},
};
end
t_insert(self.filteredData, self:GetElelementDataForAddon(addonName, info, withinHistory, overallStats, snapshotOverrides));
end
end
self.dataProvider = CreateDataProvider(self.filteredData)
if self.sortComparator then
self.dataProvider:SetSortComparator(self.sortComparator)
end
return withinHistory, overallSnapshotOverrides;
end
--- @param addonName string
--- @param info NAP_AddonInfo?
--- @param bucketsWithinHistory table<NAP_Bucket, number>
--- @param overallStats NAP_ElementData?
--- @param snapshotOverrides nil|{ encounterAvg: number, recentMs: number, peakTime: number, totalMs: number, numberOfTicks: number, applicationTotalMs: number, startMetrics: table<string, number>, endMetrics: table<string, number> }
--- @return NAP_ElementData
function NAP:GetElelementDataForAddon(addonName, info, bucketsWithinHistory, overallStats, snapshotOverrides)
--- @type NAP_ElementData
--- @diagnostic disable-next-line: missing-fields
local data = {
addonName = addonName,
addonTitle = info and info.title or '',
addonNotes = info and info.notes or '',
peakTime = 0,
averageMs = 0,
totalMs = 0,
numberOfTicks = 0,
applicationTotalMs = 0,
};
if TOTAL_ADDON_METRICS_KEY == addonName then
data.encounterAvg = snapshotOverrides and snapshotOverrides.encounterAvg or C_AddOnProfiler_GetOverallMetric(Enum_AddOnProfilerMetric_EncounterAverageTime);
data.recentMs = snapshotOverrides and snapshotOverrides.recentMs or C_AddOnProfiler_GetOverallMetric(Enum_AddOnProfilerMetric_RecentAverageTime);
else
data.encounterAvg = snapshotOverrides and snapshotOverrides.encounterAvg or C_AddOnProfiler_GetAddOnMetric(addonName, Enum_AddOnProfilerMetric_EncounterAverageTime);
data.recentMs = snapshotOverrides and snapshotOverrides.recentMs or C_AddOnProfiler_GetAddOnMetric(addonName, Enum_AddOnProfilerMetric_RecentAverageTime);
end
for _, ms in pairs(msOptions) do
data[msOptionFieldMap[ms]] = 0;
end
local now = self.frozenAt or GetTime();
local historyType = self:GetActiveHistoryRange();
if
HISTORY_TYPE_SINCE_RESET == historyType
or HISTORY_TYPE_ENCOUNTER == historyType
or HISTORY_TYPE_COMBAT == historyType
then
data.applicationTotalMs = (snapshotOverrides and snapshotOverrides.applicationTotalMs) or (now - self.resetTime) * 1000;
local currentMetrics = (snapshotOverrides and snapshotOverrides.endMetrics) or (self.frozenMetrics and self.frozenMetrics[addonName]) or self:GetCurrentMsSpikeMetrics(addonName);
local baselineMetrics = (snapshotOverrides and snapshotOverrides.startMetrics) or self.resetBaselineMetrics[addonName];
for ms in pairs(msMetricMap) do
local currentMetric = currentMetrics[ms] or 0;
local baselineMetric = baselineMetrics[ms] or 0;
local increase = currentMetric - baselineMetric;
data[msOptionFieldMap[ms]] = increase;
end
data.peakTime = snapshotOverrides and snapshotOverrides.peakTime or self.peakMs[addonName];
data.totalMs = (snapshotOverrides and snapshotOverrides.totalMs) or self.totalMs[addonName];
data.numberOfTicks = (snapshotOverrides and snapshotOverrides.numberOfTicks) or (self.tickNumber - self.loadedAtTick[addonName]);
else
local firstTickTime = now;
local lastTickTime = 0;
for bucket, startingTickIndex in pairs(bucketsWithinHistory) do
data.numberOfTicks = data.numberOfTicks + ((bucket.curTickIndex - startingTickIndex) + 1);
if bucket.tickMap[startingTickIndex] < firstTickTime then
firstTickTime = bucket.tickMap[startingTickIndex];
end
if bucket.tickMap[bucket.curTickIndex] > lastTickTime then
lastTickTime = bucket.tickMap[bucket.curTickIndex];
end
for tickIndex = startingTickIndex, bucket.curTickIndex do
local tickMs = bucket.lastTick[addonName] and bucket.lastTick[addonName][tickIndex];
if tickMs and tickMs > 0 then
if tickMs > data.peakTime then
data.peakTime = tickMs;
end
data.totalMs = data.totalMs + tickMs;
-- hardcoded for performance
if tickMs > 1 then
data.over1Ms = data.over1Ms + 1;
if tickMs > 5 then
data.over5Ms = data.over5Ms + 1;
if tickMs > 10 then
data.over10Ms = data.over10Ms + 1;
if tickMs > 50 then
data.over50Ms = data.over50Ms + 1;
if tickMs > 100 then
data.over100Ms = data.over100Ms + 1;
if tickMs > 500 then
data.over500Ms = data.over500Ms + 1;
if tickMs > 1000 then
data.over1000Ms = data.over1000Ms + 1;
end
end
end
end
end
end
end
end
end
end
data.applicationTotalMs = (lastTickTime - firstTickTime) * 1000;
end
data.averageMs = data.numberOfTicks > 0 and (data.totalMs / data.numberOfTicks) or 0; -- let's not divide by 0 :)
if self.db.mode == MODE_PASSIVE then
if TOTAL_ADDON_METRICS_KEY == addonName then
data.peakTime = (snapshotOverrides and snapshotOverrides.peakTime) or C_AddOnProfiler_GetOverallMetric(Enum_AddOnProfilerMetric_PeakTime);
else
data.peakTime = (snapshotOverrides and snapshotOverrides.peakTime) or C_AddOnProfiler_GetAddOnMetric(addonName, Enum_AddOnProfilerMetric_PeakTime);
end
end
data.overMsSum = 0;
local previousGroupCount = 0;
for _, ms in ipairs_reverse(msOptions) do
data[msOptionFieldMap[ms]] = data[msOptionFieldMap[ms]] or 0;
local count = data[msOptionFieldMap[ms]];
data.overMsSum = data.overMsSum + ((count - previousGroupCount) * ms);
previousGroupCount = count;
end
if TOTAL_ADDON_METRICS_KEY == addonName then
data.overallPeakTime = data.peakTime;
data.overallEncounterAvg = data.encounterAvg;
data.overallRecentMs = data.recentMs;
data.overallTotalMs = data.totalMs;
elseif overallStats then
data.overallPeakTime = overallStats.peakTime;
data.overallEncounterAvg = overallStats.encounterAvg;
data.overallRecentMs = overallStats.recentMs;
data.overallTotalMs = overallStats.totalMs;
end
return data;
end
function NAP:InitUI()
self.filteredData = {};
self.dataProvider = nil;
self.curMatch = ".+"
local ORDER_ASC = 1;
local ORDER_DESC = -1;
local msText = "|cff808080ms|r";
local xText = "|cff808080x|r";
local greyColorFormat = "|cff808080%s|r";
local whiteColorFormat = "|cfff8f8f2%s|r";
local TIME_FORMAT = function(val) return (val > 0.0005 and whiteColorFormat or greyColorFormat):format(("%.3f"):format(val)) .. msText; end;
local ROUND_TIME_FORMAT = function(val) return (val > 0.0005 and whiteColorFormat or greyColorFormat):format(val) .. msText; end;
local COUNTER_FORMAT = function(val) return (val > 0.0005 and whiteColorFormat or greyColorFormat):format(val) .. xText; end;
local RAW_FORMAT = function(val) return val; end;
local PERCENT_FORMAT = function(val)
local color = val > 0.00005 and whiteColorFormat or greyColorFormat;
return val >= 1 and color:format("100.00%") or color:format(("%.2f%%"):format(val * 100));
end;
local COLUMN_INFO = {};
do
local totalAddonsText = NORMAL_FONT_COLOR:WrapTextInColorCode("Total Addons");
local applicationText = NORMAL_FONT_COLOR:WrapTextInColorCode("Application");
local applicationShortText = NORMAL_FONT_COLOR:WrapTextInColorCode("App");
local Inf = math.huge
local function makeSortMethods(key)
return {
--- @param a NAP_ElementData
--- @param b NAP_ElementData
[ORDER_ASC] = function(a, b)
return (a[key] ~= Inf and a[key] < b[key]) or (a[key] == b[key] and a.addonName < b.addonName);
end,
--- @param a NAP_ElementData
--- @param b NAP_ElementData
[ORDER_DESC] = function(a, b)
return (a[key] ~= Inf and a[key] > b[key]) or (a[key] == b[key] and a.addonName < b.addonName);
end,
};
end
local counter = CreateCounter();
-- the IDs/keys should not be changed, they're persistent in SVs to remember whether they're toggled on or off
COLUMN_INFO[HEADER_IDS.addonTitle] = {
ID = HEADER_IDS.addonTitle,
order = counter(),
availableInPassiveMode = true,
justifyLeft = true,
title = "Addon Name",
width = 300,
textFormatter = RAW_FORMAT,
textKey = "addonTitle",
sortMethods = {
--- @param a NAP_ElementData
--- @param b NAP_ElementData
[ORDER_ASC] = function(a, b)
return strcmputf8i(StripHyperlinks(a.addonTitle), StripHyperlinks(b.addonTitle)) > 0
end,
--- @param a NAP_ElementData
--- @param b NAP_ElementData
[ORDER_DESC] = function(a, b)
return strcmputf8i(StripHyperlinks(a.addonTitle), StripHyperlinks(b.addonTitle)) < 0
end,
},
};
COLUMN_INFO[HEADER_IDS.encounterAvgMs] = {
ID = HEADER_IDS.encounterAvgMs,
order = counter(),
availableInPassiveMode = true,
title = "Boss Avg",
width = 96,
textFormatter = TIME_FORMAT,
textKey = "encounterAvg",
tooltip = "Average CPU time spent per frame during a boss encounter. Time based History Ranges will display the current values.",
sortMethods = makeSortMethods("encounterAvg"),
};
COLUMN_INFO[HEADER_IDS.overallEncounterAvgPercent] = {
ID = HEADER_IDS.overallEncounterAvgPercent,
order = counter(),
availableInPassiveMode = true,
title = "Boss Avg %",
width = 96,
textFormatter = PERCENT_FORMAT,
--- @param data NAP_ElementData
textFunc = function(data)
return data.overallEncounterAvg > 0 and (data.encounterAvg / data.overallEncounterAvg) or 0;
end,
tooltip = "Percentage of " .. totalAddonsText .. " CPU time spent per frame during a boss encounter. Time based History Ranges will display the current values.",
sortMethods = makeSortMethods("encounterAvg"),
};
COLUMN_INFO[HEADER_IDS.peakTimeMs] = {
ID = HEADER_IDS.peakTimeMs,
order = counter(),
availableInPassiveMode = true,
title = "Peak Time",
width = 96,
textFormatter = TIME_FORMAT,
textKey = "peakTime",
tooltip = "Biggest spike in ms, within the History Range.",
sortMethods = makeSortMethods("peakTime"),
};
COLUMN_INFO[HEADER_IDS.overallPeakTimePercent] = {
ID = HEADER_IDS.overallPeakTimePercent,
order = counter(),
availableInPassiveMode = true,
title = "Peak %",
width = 96,
textFormatter = PERCENT_FORMAT,
--- @param data NAP_ElementData
textFunc = function(data)
return data.overallPeakTime > 0 and (data.peakTime / data.overallPeakTime) or 0;
end,
tooltip = "Percentage of " .. totalAddonsText .. " biggest spike in ms, within the History Range.",
sortMethods = makeSortMethods("peakTime"),
};
COLUMN_INFO[HEADER_IDS.recentMs] = {
ID = HEADER_IDS.recentMs,
order = counter(),
availableInPassiveMode = true,
title = "Recent Ms",
width = 96,
textFormatter = TIME_FORMAT,
textKey = "recentMs",
tooltip = "Average CPU time spent in the last 60 frames. Ignores the History Range",
sortMethods = makeSortMethods("recentMs"),
};
COLUMN_INFO[HEADER_IDS.overallRecentPercent] = {
ID = HEADER_IDS.overallRecentPercent,
order = counter(),
availableInPassiveMode = true,
title = "Recent %",
width = 96,
textFormatter = PERCENT_FORMAT,
--- @param data NAP_ElementData
textFunc = function(data)
return data.overallRecentMs > 0 and (data.recentMs / data.overallRecentMs) or 0;
end,
tooltip = "Percentage of " .. totalAddonsText .. " CPU time spent in the last 60 frames. Ignores the History Range.",
sortMethods = makeSortMethods("recentMs"),
};
COLUMN_INFO[HEADER_IDS.averageMs] = {
ID = HEADER_IDS.averageMs,
order = counter(),
title = "Average",
width = 96,
textFormatter = TIME_FORMAT,
textKey = "averageMs",
tooltip = "Average CPU time spent per frame.",
sortMethods = makeSortMethods("averageMs"),