Created
March 1, 2012 04:57
-
-
Save Restuta/1947397 to your computer and use it in GitHub Desktop.
Measure.Performance (Simplifies work with Stopwatch class)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace PerformanceMeasurementMadeEasy | |
{ | |
public static class Measure | |
{ | |
private static readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); | |
/// <summary> | |
/// Will be executed at the end of each peformance measurment, by default writes elapsed ms to Console | |
/// </summary> | |
public static Action<long> WhenDone = elapsedTime => Console.WriteLine(elapsedTime + "ms"); | |
public static void Performance(Action codeToMeasure, string prefix = "") | |
{ | |
stopwatch.Reset(); | |
stopwatch.Start(); | |
codeToMeasure.Invoke(); | |
stopwatch.Stop(); | |
WhenDone.Invoke(stopwatch.ElapsedMilliseconds); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//usage example | |
//make a one-time-setup of an action you would like to perform after perf. measurement | |
Measure.WhenDone = x => Console.WriteLine("Execution time: {0}ms", x); | |
//actual sugar | |
Measure.Performance(() => | |
{ | |
for (int i = 0; i < 10000000; i++) | |
{ | |
var dict = new Dictionary<string, object>(); | |
dict["key1"] = null; | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment