Skip to content

Instantly share code, notes, and snippets.

@jeffomatic
Last active February 28, 2024 02:15
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffomatic/cfa560bad7a1163730d1b5f75f549f93 to your computer and use it in GitHub Desktop.
Save jeffomatic/cfa560bad7a1163730d1b5f75f549f93 to your computer and use it in GitHub Desktop.
Count local-thread allocations across arbitrary spans of code in Unity
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;
}
}
@jeffomatic
Copy link
Author

Usage example:

var ac = new AllocCounter();

// code that may or may not do allocations

var allocCount = ac.Stop();

Or use a lambda helper:

var allocCount = AllocCounter.Instrument(() => {
  // code that may or may not allocate
});

@jeffomatic
Copy link
Author

I wrote a little blog post that provides more context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment