public
anonymous / gist:3837601
Created

Compare list-summation code using different list structures.

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
using System;
using System.Collections.Generic;
using System.Diagnostics;
 
namespace pointers
{
class MainClass
{
private const int Iterations = 500000;
private const int Length = 10000;
 
private static void Initialize (IList<double> one, IList<double> two)
{
var rand = new Random ();
 
for (var i = 0; i < one.Count; ++i) {
one [i] = Math.Floor (rand.NextDouble () * 100);
}
 
for (var i = 0; i < two.Count; ++i) {
two [i] = Math.Floor (rand.NextDouble () * 100);
}
}
 
unsafe private static void SumUnsafeArrays (out TimeSpan duration)
{
var array1 = new double[Length];
var array2 = new double[Length];
Initialize (array1, array2);
var sw = new Stopwatch ();
sw.Start ();
 
for (var i = 0; i < Iterations; ++i) {
fixed (double *a1 = array1)
fixed (double *a2 = array2) {
double* src = a1,
dst = a2,
end = a1 + array1.Length;
 
while (src != end) {
*dst = *src;
dst++;
src++;
}
}
}
 
sw.Stop ();
 
duration = sw.Elapsed;
}
 
private static void SumSafeArrays (out TimeSpan duration)
{
var array1 = new double[Length];
var array2 = new double[Length];
var array3 = new double[Length];
 
Initialize (array1, array2);
 
var sw = new Stopwatch ();
 
sw.Start ();
 
for (var i = 0; i < Iterations; ++i) {
for (var j = 0; j < array1.Length; ++j) {
array3[j] = array1[j] + array2[j];
}
}
 
sw.Stop ();
 
duration = sw.Elapsed;
}
 
private static void SumLists (out TimeSpan duration)
{
var list1 = new List<double> (Length);
var list2 = new List<double> (Length);
 
Initialize (list1, list2);
 
var sw = new Stopwatch ();
 
sw.Start ();
 
for (var i = 0; i < Iterations; ++i) {
var list3 = new List<double> (Length);
 
for (var j = 0; j < list1.Count; ++j) {
list3.Add (list1 [j] + list2 [j]);
}
}
 
sw.Stop ();
 
duration = sw.Elapsed;
}
 
public static void Main (string[] args)
{
TimeSpan lists, safeArray, unsafeArray;
 
SumLists(out lists);
SumSafeArrays(out safeArray);
SumUnsafeArrays(out unsafeArray);
 
Console.WriteLine ("Timings: {0} iterations of {1}-item lists", Iterations, Length);
Console.WriteLine (" Lists: {0}", lists);
Console.WriteLine (" Arrays (safe): {0}", safeArray);
Console.WriteLine (" Arrays (unsafe): {0}", unsafeArray);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.