Skip to content

Instantly share code, notes, and snippets.

@matthewrdev
Last active April 2, 2020 14:39
Show Gist options
  • Save matthewrdev/04d12260f78d1404dad63bdb63bfa778 to your computer and use it in GitHub Desktop.
Save matthewrdev/04d12260f78d1404dad63bdb63bfa778 to your computer and use it in GitHub Desktop.
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