Microsoft Parallel Extensions to the .NET Framework 3.5 December 2007, Community Technology Preview
適当な演算の和を3つのコードでベンチマーク
using System; using System.Diagnostics; using System.Linq; namespace ParallelTest { class Program { const int count = 10000000; static double Single() { double sum = 0; for (int i = 0; i < count; i++) sum += Math.Pow(i, 1.1) + Math.Sin(i) * Math.Exp(Math.Sqrt(i) / (i + 1)); return sum; } static double SingleLinq() { return (from i in Enumerable.Range(0, count) select Math.Pow(i, 1.1) + Math.Sin(i) * Math.Exp(Math.Sqrt(i) / (i + 1)) ).Sum(); } static double ParallelLinq() { return (from i in ParallelEnumerable.Range(0, count) select Math.Pow(i, 1.1) + Math.Sin(i) * Math.Exp(Math.Sqrt(i) / (i + 1)) ).Sum(); } delegate double TestAction(); static void Benchmark(TestAction action) { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); var sum = action(); stopwatch.Stop(); Console.WriteLine("{0}:\n\tspan={1} result={2}", action.Method, stopwatch.Elapsed, sum); } static void Main(string[] args) { Benchmark(Single); Benchmark(SingleLinq); Benchmark(ParallelLinq); } } }
ParallelEnumerableがParallel Extensionsの「System.Threading.dll」に依存しています。
結果
Double Single(): span=00:00:02.5064016 result=238660562382214 Double SingleLinq(): span=00:00:02.7908246 result=238660562382214 Double ParallelLinq(): span=00:00:01.8028562 result=238660562382206
効果が得られるようなループ数と計算量にしています。計算結果のずれは並列のために分割されて演算順序が変わることによる誤差なんでしょう。