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 = "";
            }
        }
    }

Enjoy.

If you made it this far, you should follow me on Twitter.

-JP

Want to test-drive Bitcoin without any risk? Check out my bitcoin wallet Coinbolt. It includes test coins for free.

comments powered by Disqus