Skip to main content

Simple C# class to test a method efficiency.

using System;
using System.Diagnostics;

namespace WindowsApplication1
{
    public class SpeedTester
    {
        public delegate void MethodHandler();
        private int totalRunningTime;
        private double averageRunningTime;

        public int TotalRunningTime
        {
            get
            {
                return totalRunningTime;
            }
        }

        public double AverageRunningTime
        {
            get
            {
                return averageRunningTime;
            }
        }

        private MethodHandler method;

        public SpeedTester(MethodHandler methodToTest)
        {
            this.method = methodToTest;
        }

        public void RunTest()
        {
            RunTest(10000); //default 10,000 trials
        }

        public void RunTest(int trials)
        {
            Stopwatch watch = new Stopwatch();

            watch.Start();
            for (int i = 0; i < trials; i++)
            {
                method.Invoke(); //run the method
            }
            watch.Stop();

            totalRunningTime = (int)watch.ElapsedMilliseconds; //total milliseconds
            averageRunningTime = (double)TotalRunningTime / trials; //total time over number of trials
        }
    }
}

//
// Usage
//
// The class can be downloaded at the bottom of the page. Let's talk for a second
// about how to use it. The initializer works like this:

SpeedTester myTest = new SpeedTester([method to test]);
myTest.RunTest();

// Notice how convenient it is to pass an entire method as a parameter. But there
// is a catch, the method passed but be a void method with no parameters. So how
// would you test a C# method that takes a string as a parameter and returns in
// integer for example?
//
// Simple, write a wrapper method. For example:

private void myWrapperCall()
{
     int i = myMethod("some-long-string-to-test-for-speed-and-efficiency");
}

// Then the SpeedTester class would run on myWrapperCall. This flexibility let's
// you decide how you want a method to be called during the performance test and
// what data it will work on.

// Additionally features are the RunTest method runs 10,000 trials by default, but
// has an overload call to let you specify exactly how many trials to run. After
// running the test, properties TotalRunningTime and AverageRunningTime give the
// appropriate running times in milliseconds so you can compare the C# code
// performance.