using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace FastLoopingConsole { class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatch(); long MaxNumber = 2500000000; ///////////////////////////////////////////////////////////// long sum = 0; sw.Restart(); sum = 0; Parallel.For(0, MaxNumber, (i) => { Interlocked.Add(ref sum, (long) Math.Sqrt(i)); }); sw.Stop(); Trace.WriteLine($"Method_1 (Parallel.For): Sum = {sum}"); Trace.WriteLine($"Elapsed time {sw.Elapsed}"); ///////////////////////////////////////////////////////////// sw.Restart(); sum = 0; var partinioner = Partitioner.Create(0, MaxNumber); Parallel.ForEach(partinioner, (range) => { long partialSum = 0; for (long i = range.Item1; i < range.Item2; i++) { partialSum += (long)Math.Sqrt(i); } Interlocked.Add(ref sum, partialSum); }); sw.Stop(); Trace.WriteLine($"Method_2 (Parallel.Foreach with partinioner): Sum = {sum}"); Trace.WriteLine($"Elapsed time {sw.Elapsed}"); ///////////////////////////////////////////////////////////// sw.Restart(); sum = 0; for (long i = 0; i < MaxNumber; i++) { sum += (long)Math.Sqrt(i); }; sw.Stop(); Trace.WriteLine($"Method_3 (Naive For): Sum = {sum}"); Trace.WriteLine($"Elapsed time {sw.Elapsed}"); } } }
Results:
Method_1 (Parallel.For): Sum = 59627479402839 Elapsed time 00:00:47.4136964 Method_2 (Parallel.Foreach with partinioner): Sum = 59627479402839 Elapsed time 00:00:02.2316763 Method_3 (Naive For): Sum = 59627479402839 Elapsed time 00:00:04.1533972