c# - C#中主线程和其他线程的基准测试

标签 c# multithreading benchmarking stopwatch

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

最佳答案

我建议你使用 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);

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

关于c# - C#中主线程和其他线程的基准测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34409798/

相关文章:

c# - 需要初始化的接口(interface)实现

c# - StackExchange.Redis - 是否可以确定端点的优先级?

c# - 如何安全地拦截自定义 Owin 中间件中的响应流

multithreading - 单独线程中的数据库连接 - 最好的方法是什么?

用于测试性能的 C++ 单元测试(综合基准)

c# - 获取列出 winRt 应用程序中的 blob

c++ - http ://tinyurl. com/pzpyvb9 处的无锁堆栈的性能数据是否真实?

c++ - 安全地取消 boost asio 截止时间计时器

mysql - 我可以在现有数据库上使用 mysqlslap 吗?

Java 内存基准测试