Пример #1
0
        /// <summary>
        /// Mesaures the execution time for the code under test.
        /// </summary>
        /// <param name="action">Code under test for which you want to measure the execution time.</param>
        /// <param name="numberOfIterations">
        /// Number of times the code under test should be executed. If this value is not null then it overrides
        /// the value provided using <see cref="ChronometerOptions"/>.
        /// </param>
        /// <returns>
        /// Returns average elapsed time in milliseconds. If UseNormalizedMean property of
        /// <see cref="ChronometerOptions"/> is set then returns the normalized elapsed time in milliseconds.
        /// </returns>
        public double Measure(Action action, int?numberOfIterations = null)
        {
            if (!Options.AllowMeasurementsUnderDebugMode && _debugModeDetector.IsInDebugMode())
            {
                throw new InvalidOperationException(
                          "Under the current Chronometer configuration, measurements are not allowed when the process is in debug mode. Please set AllowMeasurementsUnderDebugMode chronometer option to true if you would like measurements when the process is under debug mode.");
            }

            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            if (numberOfIterations.HasValue && numberOfIterations.Value < 1)
            {
                throw new ArgumentException(Properties.Resources.NumberOfIterationsLessThan1ExceptionMessage,
                                            "numberOfIterations");
            }

            _memoryOptimizer.Optimize();

            _performanceOptimizer.Optimize();

            //Warm up
            if (Options.Warmup)
            {
                action();
            }

            var timer = _timerFactory.Create(Options);

            numberOfIterations = numberOfIterations ?? Options.NumberOfInterations;
            var timings = new List <double>();

            for (var i = 0; i < numberOfIterations; i++)
            {
                timer.Restart();
                action();
                timer.Stop();

                timings.Add(timer.Elapsed.TotalMilliseconds);
            }

            _performanceOptimizer.Revert();

            return(Options.UseNormalizedMean ? _normalizedMeanCalculator.Calculate(timings) : timings.Average());
        }