Skip to content

Instantly share code, notes, and snippets.

@libin85
Forked from matthewrdev/Profiler.cs
Created March 12, 2018 23:15
Show Gist options
  • Save libin85/72f65beaafd97103a19ce50fcc4ef51a to your computer and use it in GitHub Desktop.
Save libin85/72f65beaafd97103a19ce50fcc4ef51a 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