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