Perform an benchmark with iterations - CSharp System

CSharp examples for System:Action

Description

Perform an benchmark with iterations

Demo Code


using System.Diagnostics;
using System;//from   w ww.  j  av a2  s  .c  o m

public class Main{
        /// <summary>
        /// Perform an <paramref name="action"/> benchmark with <paramref name="iterations"/>.
        /// </summary>
        /// <param name="action">The action to perform.</param>
        /// <param name="iterations">The amount of iterations.</param>
        /// <returns>The amount of time taken.</returns>
        public static double Benchmark(Action action, int iterations)
        {
            double time = 0;
            const int innerCount = 5;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            for (var i = 0; i < innerCount; i++)
                action.Invoke();

            var watch = Stopwatch.StartNew();

            for (var i = 0; i < iterations; i++)
            {
                action.Invoke();
                time += Convert.ToDouble(watch.ElapsedMilliseconds) / Convert.ToDouble(iterations);
            }

            return time;
        }
}

Related Tutorials