Skip to content

Instantly share code, notes, and snippets.

@andy-williams
Created January 14, 2016 15:38
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 andy-williams/66df8ead11ed4aa2cf13 to your computer and use it in GitHub Desktop.
Save andy-williams/66df8ead11ed4aa2cf13 to your computer and use it in GitHub Desktop.
Embarrassingly parallel problem solved with different approaches
void Main()
{
Stopwatch sw;
var ints = Enumerable.Range(0, 25000);
Func<int, double> func = (x) => {
double result = 0;
for(var i = 0; i < x; i++) {
result += Math.Cos(i);
}
return result;
};
// sequential
sw = Stopwatch.StartNew();
var result1 = ints.Select(x => func(x)).Sum();
sw.Stop();
result1.Dump();
sw.Elapsed.Dump();
// PLINQ
sw = Stopwatch.StartNew();
var result2 = ints.AsParallel().Select(x => func(x)).Sum();
sw.Stop();
result2.Dump();
sw.Elapsed.Dump();
// map-reduce
double result3 = 0;
var obj = new Object();
sw = Stopwatch.StartNew();
var task = Parallel.ForEach(ints,
() => new List<double>(),
(data, loopControl, localList) =>
{
localList.Add(func(data));
return localList;
},
(localList) =>
{
lock(obj)
{
result3 += localList.Sum();
}
});
sw.Stop();
result3.Dump();
sw.Elapsed.Dump();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment