/* * Util.Benchmarker.cs * Authors: Adam Nabinger * Copyright (c) 2007-2008 Cornell University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if DEBUG using System.Diagnostics; using System.Globalization; namespace Util { /// /// For Testing. /// public delegate void TestFunction(); /// /// This is a test class, used for comparing the performance of two selections of code. /// public static class Benchmarker { /// /// For Testing. Compare the relative performance of two functions. /// public static void FightToTheDeath(TestFunction alpha, TestFunction beta) { unchecked { Stopwatch timer = new Stopwatch(); timer.Start(); // Exercise the JIT while (timer.Elapsed.TotalMilliseconds < 1000) { alpha(); beta(); } timer.Stop(); timer.Reset(); // Start timing double AlphaTotal = 0; double BetaTotal = 0; int n = 1; for (; ; ) { timer.Start(); for (int i = n; i > 0; --i) { alpha(); } timer.Stop(); double timeA = timer.Elapsed.TotalMilliseconds; System.Console.Write("Alpha: "); System.Console.WriteLine(timeA); AlphaTotal += timeA; timer.Reset(); timer.Start(); for (int i = n; i > 0; --i) { beta(); } timer.Stop(); double timeB = timer.Elapsed.TotalMilliseconds; System.Console.Write("Beta : "); System.Console.WriteLine(timeB); BetaTotal += timeB; timer.Reset(); double diff = AlphaTotal - BetaTotal; if (diff < 0) { diff = -diff; System.Console.Write("Alpha is faster by "); System.Console.Write(diff); System.Console.Write(" - "); System.Console.WriteLine(((2 * diff) / (AlphaTotal + BetaTotal)).ToString("P0", CultureInfo.CurrentCulture)); } else { System.Console.Write("Beta is faster by "); System.Console.Write(diff); System.Console.Write(" - "); System.Console.WriteLine(((2 * diff) / (AlphaTotal + BetaTotal)).ToString("P0", CultureInfo.CurrentCulture)); } n = n << 1; if (n <= 0) { return; } } } } } } #endif