Created
January 14, 2016 15:38
-
-
Save andy-williams/66df8ead11ed4aa2cf13 to your computer and use it in GitHub Desktop.
Embarrassingly parallel problem solved with different approaches
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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