2013-12-09 133 views
0

我在比较线程和非线程应用程序,如何以及为什么非线程应用程序更快?为什么非线程工作比多线程更快?

// makes thread 
private void MakeThreads(int n) 
{ 
    for (int i = 0; i < n; i++) 
    { 
     Thread thread = new Thread(PerformOperation); 
     _threads.Add(thread); 
     thread.Start(); 
    } 
} 

// any operation 
private void PerformOperation() 
{ 
    int j = 0; 
    for (int i = 0; i < 999999; i++) 
    { 
     j++; 
    } 
} 

private void Threaded_Click(object sender, EventArgs e) 
{ 
    const int outer = 1000; 
    const int inner = 2; 

    Stopwatch timer = Stopwatch.StartNew(); 
    for (int i = 0; i < outer; i++) 
    { 
     MakeThreads(inner); 
    } 
    timer.Stop(); 
    TimeSpan timespan = timer.Elapsed; 

    MessageBox.Show("Time Taken by " + (outer * inner) + " Operations: " + 
     String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10), 
     "Result", 
     MessageBoxButtons.OK, 
     MessageBoxIcon.Information); 
} 

private void NonThreaded_Click(object sender, EventArgs e) 
{ 
    const int outer = 1000; 
    const int inner = 2; 

    Stopwatch timer = Stopwatch.StartNew(); 
    for (int i = 0; i < inner * outer; i++) 
    { 
     PerformOperation(); 
    } 
    timer.Stop(); 
    TimeSpan timespan = timer.Elapsed; 

    MessageBox.Show("Time Taken by " + (outer * inner) + " Operations: " + 
     String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10), 
     "Result", 
     MessageBoxButtons.OK, 
     MessageBoxIcon.Information); 
} 

螺纹时间:○点19分43秒 非螺纹时间:00:08:72

为什么我的线程被占用太多的时间?我犯了一些错误吗?

回答

3

因为您创建的线程太多。创建线程需要更多时间,同时你的代码也是错误的,你不会等待线程完成。

private void Threaded_Click(object sender, EventArgs e) 
{ 
    const int outer = 1000; 
    const int inner = 2; 

    Stopwatch timer = Stopwatch.StartNew(); 
    Parallel.For(0, inner*outer, i=> { 

     PerformOperation(); 
    }); 
    timer.Stop(); 
    TimeSpan timespan = timer.Elapsed; 

    MessageBox.Show("Time Taken by " + (outer * inner) + " Operations: " + 
     String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10), 
     "Result", 
     MessageBoxButtons.OK, 
     MessageBoxIcon.Information); 
} 
+0

如果我等待一个线程完成,那么多线程的优势是什么? – sms247

+0

你不等待单线程,你正在等待所有人完成。先试试这个,然后告诉我你是否没有注意到优势。 –

+0

现在,这是我真正想要的。谢谢,这工作。 – sms247

2

方法“Threaded_Click()”将在后台线程(非UI线程)的线程上执行代码。虽然方法“NonThreaded_Click()”将在UI线程(前台线程)上执行代码。 这就是它比其他人更早执行的原因。

你可以让他们都通过使变化对相同的时间间隔执行“MakeThreads()”,如下

private void MakeThreads(int n) 
     { 
      for (int i = 0; i < n; i++) 
      {     
       var task = Task.Factory.StartNew(PerformOperation);    
       task.Wait(); 
      } 
     } 

但是,这将冻结UI线程。

+0

这也有帮助谢谢。它已经最小化了时间。但是Akash Kava的回答是最好的 – sms247

相关问题