Here is a simple class that will help you measure the code execution time:
public class PerformanceTester : IDisposable { private Stopwatch _stopwatch = new Stopwatch(); private Action<TimeSpan> _callback; public PerformanceTester() { _stopwatch.Start(); } public PerformanceTester(Action<TimeSpan> callback) : this() { _callback = callback; } public static PerformanceTester Start(Action<TimeSpan> callback) { return new PerformanceTester(callback); } public void Dispose() { _stopwatch.Stop(); if (_callback != null) _callback(Result); } public TimeSpan Result { get { return _stopwatch.Elapsed; } } }
Usage (only code block code using PerformanceTester ):
using (var tester = new PerformanceTester()) {
If you specify the tester variable before the using block, then the stopwatch will automatically stop when you exit the using block, and the results will be available to you:
PerformanceTester tester; using (tester = new PerformanceTester()) SomeAction(); MessageBox.Show(tester.Results.ToString());
If you pass the callback action to PerformanceTester , this action will be called at the end of the using statement, and the elapsed time will be passed to the callback:
using (PerformanceTester.Start(ts => MessageBox.Show(ts.ToString()))) SomeAction();
You can declare a method that takes a TimeSpan and processes the results:
private void ProcessResult(TimeSpan span) {
Usage becomes very clean:
using (PerformanceTester.Start(ProcessResult)) SomeAction();
Sergey Berezovskiy
source share