Advertisement
Guest User

Weird performance increase in simple benchmark

a guest
Aug 20th, 2015
970
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.CompilerServices;
  4.  
  5. public static class CSharpTest
  6. {
  7.     private const int ITERATIONS = 1000 * 1000 * 1000;
  8.  
  9.  
  10.    
  11.     public static void Main()
  12.     {
  13.         PrerequisiteCheck();
  14.  
  15.         Console.WriteLine("running...");
  16.  
  17.         Test1();
  18.         Test2();
  19.  
  20.         Console.WriteLine();
  21.  
  22.         Test1();
  23.         Test2();
  24.  
  25.         Console.WriteLine("all done");
  26.     }
  27.  
  28.     // I am having the issue with .NET 4.5.2 x86
  29.     private static void PrerequisiteCheck()
  30.     {
  31.         if (Environment.Version.Major < 4)
  32.             throw new InvalidOperationException("it seems you need a higher .net version");
  33.        
  34.         if (Environment.Is64BitProcess)
  35.             throw new InvalidOperationException("try setting the platform to x86 instead");
  36.        
  37. #if DEBUG
  38.         throw new InvalidOperationException("and btw this is not a release build");
  39. #endif
  40.     }
  41.  
  42.     private static void Test1()
  43.     {
  44.         Point a = new Point(1, 1), b = new Point(1, 1);
  45.  
  46.         var sw = Stopwatch.StartNew();
  47.         for (int i = 0; i < ITERATIONS; i++)
  48.             a = AddByVal(a, b);
  49.         sw.Stop();
  50.  
  51.         Console.WriteLine("Test1: x={0} y={1}, Time elapsed: {2} ms", a.X, a.Y, sw.ElapsedMilliseconds);
  52.     }
  53.  
  54.     private static void Test2()
  55.     {
  56.         var magical_speed_booster = Stopwatch.StartNew();
  57.  
  58.         {
  59.             Point a = new Point(1, 1), b = new Point(1, 1);
  60.  
  61.             var sw = Stopwatch.StartNew();
  62.             for (int i = 0; i < ITERATIONS; i++)
  63.                 a = AddByVal(a, b);
  64.             sw.Stop();
  65.  
  66.             Console.WriteLine("Test2: x={0} y={1}, Time elapsed: {2} ms", a.X, a.Y, sw.ElapsedMilliseconds);
  67.         }
  68.  
  69.         magical_speed_booster.Stop();
  70.     }
  71.  
  72.     [MethodImpl(MethodImplOptions.AggressiveInlining)]
  73.     private static Point AddByVal(Point a, Point b)
  74.     {
  75.         return new Point(a.X + b.Y, a.Y + b.X);
  76.     }
  77. }
  78.  
  79. public struct Point
  80. {
  81.     public Point(double x, double y) { X = x; Y = y; }
  82.     public readonly double X;
  83.     public readonly double Y;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement