Warum ist PLINQ für diesen Code langsamer als LINQ?
Zunächst starte ich dies auf einem Dual-Core-2,66-GHz-Prozessor. Ich bin nicht sicher, ob ich den Aufruf von .AsParallel () an der richtigen Stelle habe. Ich habe es auch direkt auf der Bereichsvariablen versucht und das war noch langsamer. Ich verstehe nicht warum ...
Hier sind meine Ergebnisse:
Prozess nicht parallel 1000 dauerte 146 Millisekunden
Prozess parallel 1000 dauerte 156 Millisekunden
Prozess nicht parallel 5000 dauerte 5187 Millisekunden
Prozess parallel 5000 dauerte 5300 Millisekunden
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace DemoConsoleApp
{
internal class Program
{
private static void Main()
{
ReportOnTimedProcess(
() => GetIntegerCombinations(),
"non-parallel 1000");
ReportOnTimedProcess(
() => GetIntegerCombinations(runAsParallel: true),
"parallel 1000");
ReportOnTimedProcess(
() => GetIntegerCombinations(5000),
"non-parallel 5000");
ReportOnTimedProcess(
() => GetIntegerCombinations(5000, true),
"parallel 5000");
Console.Read();
}
private static List<Tuple<int, int>> GetIntegerCombinations(
int iterationCount = 1000, bool runAsParallel = false)
{
IEnumerable<int> range = Enumerable.Range(1, iterationCount);
IEnumerable<Tuple<int, int>> integerCombinations =
from x in range
from y in range
select new Tuple<int, int>(x, y);
return runAsParallel
? integerCombinations.AsParallel().ToList()
: integerCombinations.ToList();
}
private static void ReportOnTimedProcess(
Action process, string processName)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
process();
stopwatch.Stop();
Console.WriteLine("Process {0} took {1} milliseconds",
processName, stopwatch.ElapsedMilliseconds);
}
}
}