Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- namespace NumericPerfTestCSharp {
- class Program {
- static void Main() {
- var collection = new int[100000000];
- Benchmark(() => SumForEach(collection), "SumForEach");
- Benchmark(() => SumFor(collection), "SumFor");
- }
- static long SumForEach(int[] collection) {
- long sum = 0;
- foreach (var i in collection) {
- sum += i;
- }
- return sum;
- }
- static long SumFor(int[] collection) {
- long sum = 0;
- for (int i = 0; i < collection.Length; ++i) {
- sum += collection[i];
- }
- return sum;
- }
- static void Benchmark<T>(Func<T> func, string message) {
- // warm-up call
- func();
- var sw = new Stopwatch();
- for (int i = 0; i < 5; ++i) {
- sw.Start();
- var res = func();
- sw.Stop();
- // Write result just to prevent the compiler from optimising away the method call
- Console.Write(res);
- }
- Console.Write('\n');
- Console.WriteLine(message + " : {0} ms", sw.ElapsedMilliseconds);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement