【发布时间】:2013-12-09 06:12:45
【问题描述】:
我在比较线程和非线程应用程序,为什么非线程应用程序更快?
// 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);
}
线程时间:00:19:43 非线程时间:00:08:72
为什么我的线程花费了太多时间?我是不是搞错了?
【问题讨论】:
标签: c# multithreading