Skip to content

Instantly share code, notes, and snippets.

@cameronsjo
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save cameronsjo/df267ba72bf61d5045e5 to your computer and use it in GitHub Desktop.

Select an option

Save cameronsjo/df267ba72bf61d5045e5 to your computer and use it in GitHub Desktop.
public static void TimedTest(Action action, string message = "", int decimalPlaces = 1)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
action.Invoke();
stopwatch.Stop();
double elapsed = stopwatch.ElapsedTicks / Stopwatch.Frequency;
var time = stopwatch.ElapsedTicks * 1e-9 + " ms" + " (" + stopwatch.ElapsedTicks + " ticks)";
if (String.IsNullOrWhiteSpace(message))
Console.WriteLine("Elapsed time: " + time);
else
Console.WriteLine(string.Format("{0} (Elapsed time: {1})", message, time));
}
public static void TimedTest(Action action, string message = "", int decimalPlaces = 1)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
action.Invoke();
stopwatch.Stop();
// ReSharper disable once PossibleLossOfFraction
double elapsed = stopwatch.ElapsedTicks / Stopwatch.Frequency;
string time;
if (elapsed > 1)
time = Math.Round(elapsed, decimalPlaces) + " s";
else if (elapsed > 1e-3)
time = Math.Round(1e3 * elapsed, decimalPlaces) + " ms";
else if (elapsed > 1e-6)
time = Math.Round(1e6 * elapsed, decimalPlaces) + " µs";
else if (elapsed > 1e-9)
time = Math.Round(1e9 * elapsed, decimalPlaces) + " ns";
else
time = stopwatch.ElapsedTicks + " ticks";
if (string.IsNullOrWhiteSpace(message))
Trace.WriteLine("Elapsed time: " + time);
else
Trace.WriteLine(string.Format("{0} (Elapsed time: {1})", message, time));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment