我在比较线程和非线程应用程序,如何以及为什么非线程应用程序更快?为什么非线程工作比多线程更快?
// 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
为什么我的线程被占用太多的时间?我犯了一些错误吗?
如果我等待一个线程完成,那么多线程的优势是什么? – sms247
你不等待单线程,你正在等待所有人完成。先试试这个,然后告诉我你是否没有注意到优势。 –
现在,这是我真正想要的。谢谢,这工作。 – sms247