为什么非线程比多线程更快?

时间:2013-12-09 06:12:46

标签: c# multithreading

我正在比较线程和非线程应用程序,非线程应用程序如何以及为何更快?

// 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

为什么我的线程花费了太多时间?我犯了一些错误吗?

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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线程。