Advertisement
Guest User

Untitled

a guest
Feb 15th, 2022
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.81 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace ThreadTest
  8. {
  9.     class Program
  10.     {
  11.         const int Count = 1_000_000;
  12.         const int Cores = 4;
  13.  
  14.         static Thread[] Threads;
  15.  
  16.         static void Main(string[] args)
  17.         {
  18.             Threads = new Thread[Cores];
  19.             var countPerThread = Count / Cores;
  20.  
  21.             for (var i = 0; i < Cores; i++)
  22.             {
  23.                 Threads[i] = new Thread(() => { ThreadFunction(i, countPerThread); });
  24.                 Threads[i].Start();
  25.                 Console.WriteLine($"Thread {i} dispatched.");
  26.             }
  27.         }
  28.  
  29.         static void ThreadFunction(int id, int count)
  30.         {
  31.             var sw = new Stopwatch();
  32.             sw.Start();
  33.  
  34.             var rand = new Random();
  35.             for (int i = 0; i < count; i++) ComputeSha256Hash(rand.Next().ToString());
  36.  
  37.             sw.Stop();
  38.             Console.WriteLine($"Finished: {sw.ElapsedMilliseconds}ms.");
  39.         }
  40.  
  41.         // Heavy task copied from https://www.c-sharpcorner.com/article/compute-sha256-hash-in-c-sharp/
  42.         static string ComputeSha256Hash(string rawData)
  43.         {
  44.             // Create a SHA256  
  45.             using (SHA256 sha256Hash = SHA256.Create())
  46.             {
  47.                 // ComputeHash - returns byte array  
  48.                 byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
  49.  
  50.                 // Convert byte array to a string  
  51.                 StringBuilder builder = new StringBuilder();
  52.                 for (int i = 0; i < bytes.Length; i++)
  53.                 {
  54.                     builder.Append(bytes[i].ToString("x2"));
  55.                 }
  56.                 return builder.ToString();
  57.             }
  58.         }
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement