0

When I use the example from MSDN:

var queryA = from num in numberList.AsParallel() select ExpensiveFunction(num); //good for PLINQ var queryB = from num in numberList.AsParallel() where num % 2 > 0 select num; //not as good for PLINQ 

My example program:

static void Main(string[] args) { // ThreadPool.SetMinThreads(100, 100); var numberList = new List<int>(); for (int i = 0; i <= 1000; i++) { numberList.Add(i); } Stopwatch sw = new Stopwatch(); sw.Start(); var queryA = from num in numberList select ExpensiveFunction(num); //good for PLINQ var c = queryA.ToList<int>(); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); var queryB = from num in numberList.AsParallel() select ExpensiveFunction(num); //good for PLINQ c = queryB.ToList<int>(); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Console.ReadKey(); } static int ExpensiveFunction(int a) { a = a + 100 - 9 + 0 + 98; // Console.WriteLine(a); return a; } 

The result is:

7 41 

Why is using AsParallel() slower than not using it?

1
  • 2
    a += 189; is NOT expensive to calculate. Commented Jun 28, 2013 at 14:42

1 Answer 1

2

Your ExpensiveFunction really isn't an expensive function for a computer.

Simple maths can be done extremely fast.

Perhaps try Thread.Sleep(500); instead. This will tell the CPU to pause for half a second which will simulate the effect of an actual expensive function.

Edit — I should state, the reason it is slower is because of the overhead parallel processing involves is more work than the actual calculation. See this answer for a better explanation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you for your answers. Hi. I understanded. Hiiiiiiiiiiiiiiiii
@user2532263 check out linqpad.net/RichClient/SampleLibraries.aspx "Asynchrony in C# 5" provides some great practical examples of parallel programming in C#.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.