Skip to content

Instantly share code, notes, and snippets.

@jonagill
Created June 28, 2018 06:42
Show Gist options
  • Save jonagill/48b7e649ab211beac0a032bf60bfbbef to your computer and use it in GitHub Desktop.
Save jonagill/48b7e649ab211beac0a032bf60bfbbef to your computer and use it in GitHub Desktop.
#if UNITY_EDITOR || DEVELOPMENT_BUILD
#define PROFILING_ENABLED
#endif
#if NET_4_6 || NET_STANDARD_2_0 || NETFX_CORE
#define NET_MODERN
#endif
using System;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.Profiling;
/// <summary>
/// Helper class for opening and closing Unity profiler samples
/// </summary>
public static class ProfilerScope
{
/// <summary>
/// Open a new Unity profiler sample. Must be called from within
/// a using statement to guarantee cleanup.
/// </summary>
public static ProfilerScopeToken Sample(
#if NET_MODERN && PROFILING_ENABLED
[System.Runtime.CompilerServices.CallerMemberName]
string callerMember = ""
#endif
)
{
#if PROFILING_ENABLED
string sampleName;
#if NET_MODERN
sampleName = callerMember;
#else
var frame = new StackFrame(1);
var callingMethod = frame.GetMethod();
sampleName = callingMethod.Name;
#endif
Profiler.BeginSample(sampleName);
#endif
return new ProfilerScopeToken();
}
/// <summary>
/// Disposable token for closing the current profiler scope
/// Has to be a struct to prevent GC generation in release builds
/// </summary>
public struct ProfilerScopeToken : IDisposable
{
#if PROFILING_ENABLED
bool disposed;
#endif
public void Dispose()
{
#if PROFILING_ENABLED
if (disposed)
{
return;
}
disposed = true;
Profiler.EndSample();
#endif
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment