Skip to content

Instantly share code, notes, and snippets.

Created October 5, 2012 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3837601 to your computer and use it in GitHub Desktop.
Save anonymous/3837601 to your computer and use it in GitHub Desktop.
Compare list-summation code using different list structures.
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment