【问题标题】:Benchmark for main thread and other thread in C#C#中主线程和其他线程的基准测试
【发布时间】:2016-03-28 08:39:38
【问题描述】:

我遇到了一个问题,要演示使用单线程和多线程执行函数的基准。 我在这里做吗?如果是,我怎么能不使用 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

【问题讨论】:

    标签: c# multithreading benchmarking stopwatch


    【解决方案1】:

    我建议您使用Tasks 和方法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);
    

    在您的解决方案中没有并行工作,所有线程都是一个接一个地执行。

    【讨论】:

    • 我不推荐使用Task.Factory.StartNew,而是使用Task.Run,当你使用StartNew而不通过时,很容易意外地在UI线程而不是线程池上运行东西在调度器中,Task.Run 总是使用线程池调度器。
    • 它就像魅力一样。 :) 但我想知道为什么我的代码不能并行工作。线程不是为了实现并行吗?
    • 感谢您的即时回复。你拯救了我的一天。 :) 我不能使用 Thread 本身来实现结果吗?
    • @NaveenKumarV 您的代码不会并行运行,因为您一启动就等待每个线程。如果你坚持使用Thread 而不是Task,试试这个:t1.Start(); t2.Start(); t3.Start(); t1.Join();t2.Join();t3.Join();
    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    相关资源
    最近更新 更多