Skip to content

anonymous /gist:3837601

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.