Skip to content

Instantly share code, notes, and snippets.

@Buildstarted
Last active January 2, 2016 01:09
Show Gist options
  • Save Buildstarted/8228283 to your computer and use it in GitHub Desktop.
Save Buildstarted/8228283 to your computer and use it in GitHub Desktop.
Simple wrapper to measure how long it takes to run a block of code.
public void Test() {
using(Measure.Step("Retrieve something from database")) {
...
}
}
//This will output to the debug console
//"Retrieve something from database: 00:00:00.324"
public static class Measure
{
public static bool PerformMeasure = true;
public static MeasureInst Step()
{
return new MeasureInst();
}
public static MeasureInst Step(string name)
{
return new MeasureInst(name);
}
}
public sealed class MeasureInst : IDisposable
{
private static readonly Stopwatch Stopwatch = Stopwatch.StartNew();
private readonly string _name;
private readonly long _startTicks;
public MeasureInst()
{
this._startTicks = Stopwatch.ElapsedTicks;
}
public MeasureInst(string name) : this()
{
this._name = name;
}
public void Dispose()
{
if (Measure.PerformMeasure)
{
Debug.WriteLine("{0}{1}", string.IsNullOrEmpty(this._name) ? "" : this._name + ": ", new TimeSpan(Stopwatch.ElapsedTicks - this._startTicks));
}
}
}
internal class Stopwatch
{
private readonly System.Diagnostics.Stopwatch _stopwatch;
public static Stopwatch StartNew()
{
return new Stopwatch();
}
private Stopwatch()
{
this._stopwatch = System.Diagnostics.Stopwatch.StartNew();
}
public long ElapsedTicks
{
get { return this._stopwatch.ElapsedTicks; }
}
public long ElapsedMilliseconds
{
get { return this._stopwatch.ElapsedMilliseconds; }
}
public TimeSpan Elapsed
{
get { return this._stopwatch.Elapsed; }
}
public bool IsRunning
{
get { return this._stopwatch.IsRunning; }
}
public void Stop()
{
this._stopwatch.Stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment