Facebook
From Filip Wicha, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 247
  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.  
  11.         static System.Object locker = new System.Object();
  12.         static public ulong sum = 0;
  13.         static public int[] _tab;
  14.  
  15.         static public void randomTable(int size)
  16.         {
  17.             int[] tab = new int[size];
  18.  
  19.             Random randomNumber = new Random();
  20.  
  21.             for (int i = 0; i < size; i++)
  22.             {
  23.                 tab[i] = randomNumber.Next(0, 100);
  24.             }
  25.            
  26.             normalSum(tab);
  27.             Console.WriteLine();
  28.             parallelSum(tab);
  29.         }
  30.  
  31.         static public void normalSum(int[] tab)
  32.         {
  33.             int sum = 0;
  34.             Stopwatch stoper = new Stopwatch();
  35.  
  36.             stoper.Start();
  37.  
  38.             for (int i = 0; i < tab.Length; i++)
  39.             {
  40.                 sum += tab[i];
  41.             }
  42.  
  43.             stoper.Stop();
  44.  
  45.             Console.WriteLine("Sum (no multithreaded): " + sum);
  46.             Console.WriteLine("Time (no multithreaded): " + stoper.ElapsedMilliseconds + " ms");
  47.         }
  48.  
  49.         static public void parallelSum(int[] tab)
  50.         {
  51.             int sum = 0;
  52.             Stopwatch stoper = new Stopwatch();
  53.  
  54.             stoper.Start();
  55.  
  56.             Parallel.For(0, tab.Length,
  57.                 () => 0, (j, loop, subtotal) =>
  58.                 {
  59.                     subtotal += tab[j];
  60.                     return subtotal;
  61.                 }, (x) => Interlocked.Add(ref sum, x));
  62.  
  63.             stoper.Stop();
  64.  
  65.             Console.WriteLine("Sum (multithreaded): " + sum);
  66.             Console.WriteLine("Time (multithreaded): " + stoper.ElapsedMilliseconds + " ms");
  67.         }
  68.  
  69.  
  70.  
  71.  
  72.         static void Main(string[] args)
  73.         {
  74.             int size = 1000000;
  75.             Console.WriteLine("Size of array: " + size);
  76.             randomTable(size);
  77.             Console.ReadKey();
  78.         }
  79.     }
  80. }