using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp { class Program { const int LOOP_COUNT = 900000; static long Calcute() { int Total = 0; for (int i = 0; i < 10000; i++) // add more iteration to make parallel faster than sequential { Total += 20 * i; } return Total; } static void SequentialCalcute() { var Counter = 0; long Total = 0; Stopwatch SW = new Stopwatch(); SW.Start(); for (int i = 0; i < LOOP_COUNT; i++) { Total = Calcute(); ++Counter; } SW.Stop(); Console.WriteLine("Sequential total seconds: " + SW.Elapsed.TotalSeconds + ", Counter: " + Counter + ", Total: " + Total); } static void ParallelCalcute() { var Counter = 0; long Total = 0; Stopwatch SW = new Stopwatch(); SW.Start(); Parallel.For(0, LOOP_COUNT, i => { Total = Calcute(); Interlocked.Add(ref Counter, 1); }); SW.Stop(); Console.WriteLine("Parallel total seconds: " + SW.Elapsed.TotalSeconds + ", Counter: " + Counter + ", Total: " + Total); } static void Main(string[] args) { Console.ReadKey(); SequentialCalcute(); ParallelCalcute(); Console.ReadKey(); } } }