I was recently reading Justin Etheredge’s blog and he had a really cool post about working on a simple LINQ algorithm to make it run faster http://www.codethinked.com/post/2010/01/10/The-TekPub-LINQ-Challenge-Part-2-Faster-Algorithms.aspx. Since I am learning about LINQ, and more importantly trying to study Parallel LINQ, I decided to play with his code and use the .NET Stopwatch class to see what the performance was on my xenon core 4GB 32-bit desktop. While working on the console application, I ran across this comment:
|
Why not enumerate from 2 so that you don't have to x!=1 20,000,000 times? var primes = Enumerable.Range(2,20000000).AsParallel() .Where(x => !Enumerable.Range(2, (int)Math.Sqrt(x)).Any(y => x != y && x % y == 0)); I'm not sure of the overhead of AsParallel() but you could also try to filter out the even numbers before AsParallel with something like Enumerable.Range(2,20000000).Where(n => n % 2 != 0) - see alicebobandmallory.com/.../the-thrush-combinator-in-c for more examples. You will lose the only even prime number from the result but that could be added manually.
|
Jonas Elfström January 12. 2010 05:43 |
More...