多线程比单线程慢 [英] Multithreaded slower than singlethreaded

查看:163
本文介绍了多线程比单线程慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行矩阵乘法的程序.我有多线程和单线程版本.多线程版本比单线程版本慢,我也不知道为什么.你能给我解释一下吗?

I have a program which performs a matrix multiplication. I have multithreaded and singlethreaded versions. The multithreaded version is slower than singlethreaded and I don't know why. Could you explain me that?

多线程(对于大小= 128,秒表显示在 5 秒左右):

Multithreaded (for size = 128, stopwatch shows around 5 seconds):

private static SemaphoreSlim semaphore = new SemaphoreSlim(size, size);
(...)
for (int i = 0; i < size; i++)
{
    threads[i] = new Thread(() => Multiply(ref a, ref b, ref c));
    threads[i].Name = i.ToString();
    threads[i].Start();
}
for (int i = 0; i < size; i++)
    threads[i].Join();
(...)
public static void Multiply(ref float[,] a, ref float[,] b, ref float[,] c)
{
    int index = int.Parse(Thread.CurrentThread.Name);
    semaphore.Wait();
    for (int j = 0; j < c.GetLength(0); j++)
        for (int k = 0; k < c.GetLength(0); k++)
            c[index, j] += a[index, k] * b[k, j];
    semaphore.Release();
}

单线程(对于大小= 128,秒表显示在 3 秒左右):

Singlethreaded (for size = 128, stopwatch shows around 3 seconds):

for (int i = 0; i < size; i++)
    Multiply(i, ref a, ref b, ref c);
(...)   
public static void Multiply(int i, ref float[,] a, ref float[,] b, ref float[,] c)
{
    for (int j = 0; j < c.GetLength(0); j++)
        for (int k = 0; k < c.GetLength(0); k++)
            c[i, j] += a[i, k] * b[k, j];
}

推荐答案

这并不罕见.线程,尤其是线程同步,往往会增加很多开销.这就是为什么要仔细考虑多线程的原因,以及为什么异步而不是多线程的方法通常是正确的答案的原因.

That's not uncommon. Threads, and particularly thread synchronization, tend to add a lot of overhead. That's why multithreading is something you carefully consider, and why asynchronous but not multithreaded approaches are often the right answer.

如果您要执行CPU繁重的任务,通常最好在一个或少量工作线程上执行它们,这样它们就不会不停地抢先彼此.通常,一旦受CPU限制的线程数超过了处理器的可用内核,就不会提高性能,实际上也不会降低性能.

If you are doing CPU heavy tasks, it is often better to do them on one or a small number of worker threads so they're not just pre-empting each other nonstop. Typically there is no performance gain - and in fact a performance hit - once the number of CPU-limited threads exceeds the available cores of the processor.

想象一下,试图通过一扇门让全班幼儿园的孩子上课.实际上,让它们排成一行并有序地通过它们比让它们所有人相互推动并争取首先通过要快得多.

Imagine trying to get a class full of kindergarteners through a door to go to recess. It's actually faster to line them up and get them through in an orderly fashion than letting them all push each other out of the way and fight to get through first.

即使在线程争夺CPU时间之前,如果线程在线程上花费更多的时间,线程仍会减慢您的速度&同步开销比您通过并行执行任务所获得的开销.

Even before the point where your threads fight for CPU time, threading can still slow you down if it takes more time on thread & synchronization overhead than you gain by parallelizing the tasks.

这篇关于多线程比单线程慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆