using System; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace zad2cw2 { class Program { static System.Object lck = new System.Object(); static public ulong sum = 0; static public int[] tab; static public void randomTable(int size) { int[] tab = new int[size]; Random randomNumber = new Random(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < size; i++) { tab[i] = randomNumber.Next(0, 100); } stopwatch.Stop(); Console.WriteLine("Time of generating of a table: " + stopwatch.ElapsedMilliseconds + " ms \n"); normalSum(tab); parallelSum(tab); } static public void normalSum(int[] tab) { int sum = 0; Stopwatch stoper = new Stopwatch(); stoper.Start(); for (int i = 0; i < tab.Length; i++) { sum += tab[i]; } stoper.Stop(); Console.WriteLine("Sum sequential: " + sum); Console.WriteLine("Time sequential: " + stoper.ElapsedMilliseconds + " [ms]"); } static public void parallelSum(int[] tab) { int sum = 0; Stopwatch stoper = new Stopwatch(); stoper.Start(); Parallel.For(0, tab.Length, () => 0, (j, loop, subtotal) => { subtotal += tab[j]; return subtotal; }, (x) => Interlocked.Add(ref sum, x)); stoper.Stop(); Console.WriteLine("Sum multithreaded: " + sum); Console.WriteLine("Time multithreaded: " + stoper.ElapsedMilliseconds + " [ms]"); } static void Main(string[] args) { int size = 10; randomTable(size); Console.ReadKey(); } } }