Advertisement
Dr_Asik

Untitled

Jan 9th, 2013
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Diagnostics;
  3.  
  4. namespace NumericPerfTestCSharp {
  5.     class Program {
  6.         static void Main() {
  7.             var collection = new int[100000000];
  8.  
  9.             Benchmark(() => SumForEach(collection), "SumForEach");
  10.             Benchmark(() => SumFor(collection), "SumFor");
  11.            
  12.         }
  13.         static long SumForEach(int[] collection) {
  14.             long sum = 0;
  15.             foreach (var i in collection) {
  16.                 sum += i;
  17.             }
  18.             return sum;
  19.         }
  20.  
  21.         static long SumFor(int[] collection) {
  22.             long sum = 0;
  23.             for (int i = 0; i < collection.Length; ++i) {
  24.                 sum += collection[i];
  25.             }
  26.             return sum;
  27.         }
  28.  
  29.         static void Benchmark<T>(Func<T> func, string message) {
  30.             // warm-up call
  31.             func();
  32.  
  33.             var sw = new Stopwatch();
  34.             for (int i = 0; i < 5; ++i) {
  35.                 sw.Start();
  36.                 var res = func();
  37.                 sw.Stop();
  38.                 // Write result just to prevent the compiler from optimising away the method call
  39.                 Console.Write(res);
  40.             }
  41.             Console.Write('\n');
  42.             Console.WriteLine(message + " : {0} ms", sw.ElapsedMilliseconds);
  43.         }
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement