簡體   English   中英

C#中主線程和其他線程的基准

[英]Benchmark for main thread and other thread in C#

我給出了一個問題來演示使用Single和Multithread執行函數的基准。 我在這做嗎? 如果是,我怎么能不使用Join()。 如果沒有,建議我。

class Threading1 
{
  static void Main (string[] args) 
  {
     Stopwatch timerMain, timerThreads;

     // Main thread 
     timerMain = Stopwatch.StartNew ();
     func1();
     func2();
     func3();
     timerMain.Stop ();
     Console.WriteLine ("Time taken for Main thread: " + timerMain.ElapsedMilliseconds);

     // Other threads
     Thread t1 = new Thread (() => Threading1.func1 ());
     Thread t2 = new Thread (() => Threading1.func2 ());
     Thread t3 = new Thread (() => Threading1.func3 ());
     timerThreads = Stopwatch.StartNew ();
     t1.Start(); t1.Join();
     t2.Start(); t2.Join();
     t3.Start(); t3.Join();
     timerThreads.Stop ();
     Console.WriteLine ("Time taken for Other threads: " + timerThreads.ElapsedMilliseconds);
  }

  // Find maximum value in an array
  static void func1() 
  {
    // Code here. 
  }

  // Find minimum value in an array
  static void func2()
  {
    // Code here. 
  }

  // Find average value of an array
  static void func3()
  {
    // Code here. 
  }
}

產量

Time taken for Main thread: 44
Time taken for other threads: 10

我建議你在完成所有任務時使用任務和方法WaitAll等待。

timerThreads = Stopwatch.StartNew();
var t1 = Task.Run(() => Threading1.func1());
var t2 = Task.Run(() => Threading1.func2());
var t3 = Task.Run(() => Threading1.func3());

Task.WaitAll(t1, t2, t3);
timerThreads.Stop ();
Console.WriteLine ("Time taken for Other threads: " + timerThreads.ElapsedMilliseconds);

在你的解決方案中沒有並行工作,所有線程都是逐個執行的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM