Parallel Extensions sample
4 December 2007 in .Net, Code, Tools | Comments enabled
After yesterdays post I thought I should write up a basic sample to test the effectiveness of the Parallel Extensions. Admittedly it is a contrived example and you are unlikely to see this sort of performance increase in a real world since your applications are unlikely to be this primitive.
My sample iterates through a number sequence from 0 upwards and works out if the value is a prime number. There are two implementations, one using a standard loop and the other using a Parallel.For(). Of course, to try and ride out any spikes I iterate the tests 25 times and then average the outcome. This test is of course not run in a clean environment but does give a roughly indicative result of using the Parallel Extensions.
Using a dual core system, checking the numbers up to 100,000 and running 25 iterations of each run I had the following outcome:
Using a normal for() loop: 3104 milliseconds average per run
Using a Parallel.For() loop: 1607 milliseconds average per run
This speed up is acceptable and, as you can imagine, these sorts of results are only going to become more impressive as we move to 8, 16, 32 core systems.
A few things to consider in a real world application (consider this my “don’t blame me if you think this will solve all your problems” line! :
- Often slowness is caused by some slow resource – a web connection, a database call etc. The parallel extensions library will default to spinning up as many threads as there are cores and therefore if you have a slow dependent resource you may wish to investigate bumping up the thread count or writing your own threading code.
- The architecture of a solution is more likely to impact the overall performance of the application. Improving the speed of a few loops and LINQ queries will not improve performance by any order of magnitude.
- Amdahl’s Law applies – effectively this law states that the maximum parallel improvement that is possible for an application is limited by the amount of sequential code remaining. For example, if I can only make 10% of the code run in parallel then even with infinitive parallel processes running I’m still running slow sequential code 80% of the time – this feeds back to the previous point.
Note: You will need .Net 3.5 framework installed + the Parallel Extensions Library installed