Facebook
From Filip Wicha, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 263
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using System.Diagnostics;
  5.  
  6. namespace zad2cw2
  7. {
  8.     class Program
  9.     {
  10.         static System.Object lck = new System.Object();
  11.         static public ulong sum = 0;
  12.         static public int[] tab;
  13.  
  14.         static public void randomTable(int size)
  15.         {
  16.             int[] tab = new int[size];
  17.  
  18.             Random randomNumber = new Random();
  19.             Stopwatch stopwatch = new Stopwatch();
  20.  
  21.             stopwatch.Start();
  22.  
  23.             for (int i = 0; i < size; i++)
  24.             {
  25.                 tab[i] = randomNumber.Next(0, 100);
  26.             }
  27.  
  28.             stopwatch.Stop();
  29.  
  30.             Console.WriteLine("Time of generating of a table: " + stopwatch.ElapsedMilliseconds + " ms \n");
  31.  
  32.             normalSum(tab);
  33.             parallelSum(tab);
  34.  
  35.         }
  36.  
  37.         static public void normalSum(int[] tab)
  38.         {
  39.             int sum = 0;
  40.             Stopwatch stoper = new Stopwatch();
  41.  
  42.             stoper.Start();
  43.  
  44.             for (int i = 0; i < tab.Length; i++)
  45.             {
  46.                 sum += tab[i];
  47.             }
  48.  
  49.             stoper.Stop();
  50.  
  51.             Console.WriteLine("Sum sequential: " + sum);
  52.             Console.WriteLine("Time sequential: " + stoper.ElapsedMilliseconds + " [ms]");
  53.         }
  54.  
  55.         static public void parallelSum(int[] tab)
  56.         {
  57.             int sum = 0;
  58.             Stopwatch stoper = new Stopwatch();
  59.  
  60.             stoper.Start();
  61.  
  62.             Parallel.For(0, tab.Length,
  63.                 () => 0, (j, loop, subtotal) =>
  64.                 {
  65.                     subtotal += tab[j];
  66.                     return subtotal;
  67.                 },
  68.                         (x) => Interlocked.Add(ref sum, x));
  69.  
  70.             stoper.Stop();
  71.  
  72.             Console.WriteLine("Sum multithreaded: " + sum);
  73.             Console.WriteLine("Time multithreaded: " + stoper.ElapsedMilliseconds + " [ms]");
  74.         }
  75.  
  76.         static void Main(string[] args)
  77.         {
  78.             int size = 10;
  79.             randomTable(size);
  80.  
  81.             Console.ReadKey();
  82.         }
  83.     }
  84. }