Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple and lean profiler that measures a code section using the IDisposable pattern.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
namespace MFractor.Utilities
{
public class Profiler : IDisposable
{
readonly string Message;
private Action<string, TimeSpan> DoneHandler;
Stopwatch Watch;
public Profiler(string message, Action<string, TimeSpan> onDone = null)
{
Message = message;
#if !RELEASE
DoneHandler = onDone ?? new Action<string, TimeSpan>((content, time) =>
{
var elapsed = Math.Round(time.TotalMilliseconds, 2);
Console.WriteLine($"{content} took {elapsed}ms");
});
#endif
Watch = Stopwatch.StartNew();
}
public void Dispose()
{
DoneHandler?.Invoke(Message, Watch.Elapsed);
Watch = null;
DoneHandler = null;
}
public static Profiler Profile([CallerMemberName] string context = "", [CallerFilePath] string file = "")
{
var fileName = Path.GetFileName(file);
var profileContext = fileName + "|" + context;
return new Profiler(profileContext);
}
}
}
// Usage
public void MyMethod()
{
// Outputs "MyFile.cs | MyMethod took 20.45ms"
using (var p = Profiler.Profiler())
{
// Expensive code here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.