Benchmarking C# Apps & Algorithms

I created a class to help me benchmark my C# algorithms.

Here’s how you can use it:

BenchmarkTimer.Start("Long running algorithm");
for (int x = 0; x < 3; ++x) {
	BenchmarkTimer.Start("Small running algorithm");
	Thread.Sleep(1000);
	BenchmarkTimer.StopAndOutput();
}
BenchmarkTimer.StopAndOutput();

Output:
Small running algorithm: 1000.3712 ms
Small running algorithm: 1000.3712 ms
Small running algorithm: 1000.3712 ms
Long running algorithm: 3001.1136 ms

You can find my entire C# CommonLib library here: http://github.com/jprichardson/CommonLib

Here is the relevant class:

public static class BenchmarkTimer
	{
		private static Stack<BenchmarkData> _startStack = new Stack<BenchmarkData>();

		public static void Start() {
			_startStack.Push(new BenchmarkData());
		}

		public static void Start(string label) {
			var bd = new BenchmarkData() { Label = label };
			_startStack.Push(bd);
		}

		public static TimeSpan Stop() {
			var stop = DateTime.Now;
			var startBD = _startStack.Pop();
			return stop - startBD.DateTime;
		}

		public static void StopAndOutput() {
			var stop = DateTime.Now;
			var startBD = _startStack.Pop();

			var delta = stop - startBD.DateTime;

			var lbl = "{0}: {1} ms";
			Console.WriteLine(String.Format(lbl, startBD.Label, delta.TotalMilliseconds));
		}

		private class BenchmarkData
		{
			public DateTime DateTime { get; set; }
			public string Label { get; set; }

			public BenchmarkData(){
				this.DateTime = DateTime.Now;
				this.Label = "";
			}
		}
	}

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Follow me on Twitter: @jprichardson
Read my blog entrepreneurship: Techneur

-JP

Advertisement

One Response to Benchmarking C# Apps & Algorithms

  1. Pingback: LinkedList Always Slower than a List in C#? « Procbits

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.