-
-
Save jeffomatic/cfa560bad7a1163730d1b5f75f549f93 to your computer and use it in GitHub Desktop.
Count local-thread allocations across arbitrary spans of code in Unity
This file contains 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
using System; | |
using UnityEngine.Profiling; | |
// Borrowed directly from UnityEngine.TestTools.Constraints.AllocatingGCMemoryConstraint | |
public class AllocCounter { | |
private Recorder _rec; | |
public AllocCounter() { | |
_rec = Recorder.Get("GC.Alloc"); | |
// The recorder was created enabled, which means it captured the creation of the | |
// Recorder object itself, etc. Disabling it flushes its data, so that we can retrieve | |
// the sample block count and have it correctly account for these initial allocations. | |
_rec.enabled = false; | |
#if !UNITY_WEBGL | |
_rec.FilterToCurrentThread(); | |
#endif | |
_rec.enabled = true; | |
} | |
public int Stop() { | |
if (_rec == null) { | |
throw new Exception("AllocCounter already stopped"); | |
} | |
_rec.enabled = false; | |
#if !UNITY_WEBGL | |
_rec.CollectFromAllThreads(); | |
#endif | |
var res = _rec.sampleBlockCount; | |
_rec = null; | |
return res; | |
} | |
public static int Instrument(Action action) { | |
var counter = new AllocCounter(); | |
int allocs; | |
try { | |
action(); | |
} finally { | |
allocs = counter.Stop(); | |
} | |
return allocs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example:
Or use a lambda helper: