This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: Dr_Asik on Jan 9th, 2013  |  syntax: C#  |  size: 1.31 KB  |  views: 60  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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. }
clone this paste RAW Paste Data