-
Notifications
You must be signed in to change notification settings - Fork 17
chore: extract PerfSampler from AutoPilot for AltTester reuse #8826
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
d800d89
feat(perf): extract PerfSampler from AutoPilot for AltTester reuse
popuz 3a0b8d5
fix(perf): guard PerfSampler.PercentWorst against tiny sample windows
popuz 29e6334
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz f648f6f
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz f1c6201
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz f86d4df
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz 77c8de7
replaced debug log with report hub
popuz 5457777
Merge remote-tracking branch 'origin/feat/test-automation/autopilot-a…
popuz d7de63c
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz 61016c2
addressed AI reviewers requests
popuz e269496
Merge remote-tracking branch 'origin/feat/test-automation/autopilot-a…
popuz f58aaad
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz d71f887
wrap in try catch
popuz 4943e01
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz 649d709
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz ed80a74
Merge branch 'dev' into feat/test-automation/autopilot-alttester
popuz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 188 additions & 0 deletions
188
Explorer/Assets/DCL/PerformanceAndDiagnostics/AutoPilot/PerfSampler.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| using Cysharp.Threading.Tasks; | ||
| using DCL.Profiling; | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Globalization; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using UnityEngine; | ||
|
|
||
| namespace DCL.PerformanceAndDiagnostics.AutoPilot | ||
| { | ||
| /// <summary> | ||
| /// Per-frame CPU/GPU time sampler that mirrors the original AutoPilot CSV + | ||
| /// summary writer, but is reusable from non-AutoPilot driving code (e.g. | ||
| /// AltTester-driven scenarios). The sampler is a plain static class so that | ||
| /// it can be configured once from the plugin system and then driven by | ||
| /// multiple, sequential fixtures within a single long-lived Player session. | ||
| /// </summary> | ||
| public static class PerfSampler | ||
| { | ||
| private static IProfiler profiler; | ||
| private static StreamWriter csv; | ||
| private static string currentCsvPath; | ||
| private static string currentSummaryPath; | ||
| private static bool sampling; | ||
| private static int sampleLoopToken; | ||
|
|
||
| /// <summary> | ||
| /// Wires the profiler used to read per-frame CPU and GPU times. | ||
| /// Must be called exactly once during plugin bootstrap, BEFORE any | ||
| /// call to <see cref="Begin"/>. | ||
| /// </summary> | ||
| public static void Configure(IProfiler profiler) | ||
| { | ||
| PerfSampler.profiler = profiler; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Opens a new sampling session: writes the CSV header, remembers the | ||
| /// summary path, and kicks off the per-frame sampling loop. If a session | ||
| /// is already open this is logged and the call becomes a no-op (the | ||
| /// existing session keeps running). Throws if <see cref="Configure"/> | ||
| /// was never called. | ||
| /// </summary> | ||
| public static void Begin(string csvPath, string summaryPath) | ||
| { | ||
| if (profiler == null) | ||
| throw new InvalidOperationException( | ||
| $"{nameof(PerfSampler)}.{nameof(Configure)} must be called before {nameof(Begin)}."); | ||
|
|
||
| if (sampling) | ||
| { | ||
| DCL.Diagnostics.ReportHub.LogWarning( | ||
| DCL.Diagnostics.ReportCategory.ALWAYS, | ||
| $"{nameof(PerfSampler)}.{nameof(Begin)} called while a sampling session is already active. Ignoring."); | ||
| return; | ||
| } | ||
|
|
||
| if (string.IsNullOrEmpty(csvPath)) | ||
| throw new ArgumentException("CSV path is required", nameof(csvPath)); | ||
|
|
||
| csv = new StreamWriter(csvPath, false, new UTF8Encoding(false)); | ||
| csv.NewLine = "\r\n"; // https://www.rfc-editor.org/rfc/rfc4180 | ||
| csv.WriteLine("\"Frame\",\"CPU Time\",\"GPU Time\""); | ||
|
|
||
| currentCsvPath = csvPath; | ||
| currentSummaryPath = summaryPath; | ||
| sampling = true; | ||
|
|
||
| int token = ++sampleLoopToken; | ||
| SampleLoopAsync(token).Forget(); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Closes the current sampling session: stops the sample loop, flushes | ||
| /// and closes the CSV, then (if a summary path was given) writes the | ||
| /// 8-line summary file. No-op if there is no open session. | ||
| /// </summary> | ||
| public static void End() | ||
| { | ||
| if (!sampling) | ||
| return; | ||
|
|
||
| sampling = false; | ||
|
|
||
| try | ||
| { | ||
| csv?.Dispose(); | ||
| } | ||
| finally | ||
| { | ||
| csv = null; | ||
| } | ||
|
|
||
| if (!string.IsNullOrEmpty(currentSummaryPath)) | ||
| WriteSummary(currentCsvPath, currentSummaryPath); | ||
|
|
||
| currentCsvPath = null; | ||
| currentSummaryPath = null; | ||
| } | ||
|
|
||
| private static async UniTaskVoid SampleLoopAsync(int token) | ||
| { | ||
| try | ||
| { | ||
| while (sampling && token == sampleLoopToken) | ||
| { | ||
| WriteSample(); | ||
| await UniTask.Yield(); | ||
| } | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| DCL.Diagnostics.ReportHub.LogException(e, DCL.Diagnostics.ReportCategory.ALWAYS); | ||
| sampling = false; | ||
| } | ||
|
popuz marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private static void WriteSample() | ||
| { | ||
| if (csv == null) | ||
| return; | ||
|
|
||
| csv.WriteLine(string.Format( | ||
| CultureInfo.InvariantCulture, "{0},{1},{2}", | ||
| Time.frameCount, | ||
| profiler.LastFrameTimeValueNs * 0.000001f, | ||
| profiler.LastGpuFrameTimeValueNs * 0.000001f)); | ||
| } | ||
|
|
||
| private static void WriteSummary(string csvFile, string summaryFile) | ||
| { | ||
| var cpuTimes = new List<float>(); | ||
| var gpuTimes = new List<float>(); | ||
|
|
||
| using (var reader = new StreamReader(csvFile)) | ||
| { | ||
| reader.ReadLine(); // Discard the header line | ||
|
|
||
| while (!reader.EndOfStream) | ||
| { | ||
| string line = reader.ReadLine(); | ||
| if (line == null) break; | ||
| string[] columns = line.Split(','); | ||
| cpuTimes.Add(float.Parse(columns[1], CultureInfo.InvariantCulture)); | ||
| gpuTimes.Add(float.Parse(columns[2], CultureInfo.InvariantCulture)); | ||
| } | ||
| } | ||
|
|
||
| using (var summary = new StreamWriter(summaryFile)) | ||
| { | ||
| summary.Write("CPU average: "); | ||
| summary.WriteLine(cpuTimes.Average().ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("CPU 1% worst: "); | ||
| summary.WriteLine(PercentWorst(cpuTimes, 0.01f).ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("CPU 0.1% worst: "); | ||
| summary.WriteLine(PercentWorst(cpuTimes, 0.001f).ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("CPU worst: "); | ||
| summary.WriteLine(cpuTimes.Max().ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("GPU average: "); | ||
| summary.WriteLine(gpuTimes.Average().ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("GPU 1% worst: "); | ||
| summary.WriteLine(PercentWorst(gpuTimes, 0.01f).ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("GPU 0.1% worst: "); | ||
| summary.WriteLine(PercentWorst(gpuTimes, 0.001f).ToString(CultureInfo.InvariantCulture)); | ||
| summary.Write("GPU worst: "); | ||
| summary.WriteLine(gpuTimes.Max().ToString(CultureInfo.InvariantCulture)); | ||
| } | ||
| } | ||
|
|
||
| /// <remarks> | ||
| /// As done by GamersNexus: | ||
| /// https://www.youtube.com/watch?v=WcTxrzFqdyw#t=34m17s | ||
| /// </remarks> | ||
| private static float PercentWorst(List<float> times, float fraction) | ||
| { | ||
| // Short sampling windows can yield < 1/fraction samples (e.g. an | ||
| // InWorld fixture that runs ~15s at ~30 FPS produces ~450 samples, | ||
| // so (int)(450 * 0.001f) is 0 and Take(0).Average() throws). Floor | ||
| // the count to 1 so 0.1% worst on small windows just reports the | ||
| // single worst frame instead of crashing summary generation. | ||
| if (times.Count == 0) return 0f; | ||
| var k = Math.Max(1, (int)(times.Count * fraction)); | ||
| return times.OrderByDescending(i => i).Take(k).Average(); | ||
|
popuz marked this conversation as resolved.
popuz marked this conversation as resolved.
popuz marked this conversation as resolved.
popuz marked this conversation as resolved.
popuz marked this conversation as resolved.
popuz marked this conversation as resolved.
popuz marked this conversation as resolved.
|
||
| } | ||
| } | ||
| } | ||
3 changes: 3 additions & 0 deletions
3
Explorer/Assets/DCL/PerformanceAndDiagnostics/AutoPilot/PerfSampler.cs.meta
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.