.Net中的多线程性能不佳 [英] Poor multithreading performance in .Net
问题描述
为什么我会从下面的代码中获得如此糟糕的性能?
Why would I be getting such poor performance from the code below?
以下命令行使用16个线程,负载为60. 在我的计算机上,这大约需要31秒才能完成(如果您重新运行,可能会有一些细微的变化)
The following command line uses 16 threads, with a load of 60. On my machine this takes approximately 31 seconds to finish (with some slight variations if you rerun)
testapp.exe 16 60
在60个负载下,在16个Intel Xeon E5-2670 @ 2.6 GHz CPU上运行的Microsoft Windows Server 2008 R2 Enterprise SP1上,我获得以下性能:
Using a load of 60, on Microsoft Windows Server 2008 R2 Enterprise SP1, running on 16 Intel Xeon E5-2670 @ 2.6 GHz CPUs I get the following performance:
1 cpu-305秒
1 cpu - 305 seconds
2 cpus-155秒
2 cpus - 155 seconds
4 cpus-80秒
4 cpus - 80 seconds
8 cpus-45秒
8 cpus - 45 seconds
10 cpus-41秒
10 cpus - 41 seconds
12 cpus-37秒
12 cpus - 37 seconds
14 cpus-34秒
14 cpus - 34 seconds
16 cpus-31秒
16 cpus - 31 seconds
18 cpus-27秒
18 cpus - 27 seconds
20 cpus-24秒
20 cpus - 24 seconds
22 cpus-23秒
22 cpus - 23 seconds
24 cpus-21秒
24 cpus - 21 seconds
26 cpus-20秒
26 cpus - 20 seconds
28 cpus-19秒
28 cpus - 19 seconds
在此之后,它变平线...
After this it flat-lines ...
使用.Net 3.5、4、4.5或4.5.1可获得大致相同的性能.
I get approximately the same performance using .Net 3.5, 4, 4.5 or 4.5.1.
我了解22 cpus之后的性能下降,因为我盒子上只有16 cpus.我不明白的是8 cpus后的性能不佳.谁能解释?这正常吗?
I understand the drop-off in performance after 22 cpus, as I only have 16 on the box. What I don't understand is the poor performance after 8 cpus. Can anyone explain? Is this normal?
private static void Main(string[] args)
{
int threadCount;
if (args == null || args.Length < 1 || !int.TryParse(args[0], out threadCount))
threadCount = Environment.ProcessorCount;
int load;
if (args == null || args.Length < 2 || !int.TryParse(args[1], out load))
load = 1;
Console.WriteLine("ThreadCount:{0} Load:{1}", threadCount, load);
List<Thread> threads = new List<Thread>();
for (int i = 0; i < threadCount; i++)
{
int i1 = i;
threads.Add(new Thread(() => DoWork(i1, threadCount, load)));
}
Stopwatch timer = Stopwatch.StartNew();
foreach (var thread in threads)
{
thread.Start();
}
foreach (var thread in threads)
{
thread.Join();
}
timer.Stop();
Console.WriteLine("Time:{0} seconds", timer.ElapsedMilliseconds/1000.0);
}
static void DoWork(int seed, int threadCount, int load)
{
double[,] mtx = new double[3,3];
for (int i = 0; i < ((100000 * load)/threadCount); i++)
{
for (int j = 0; j < 100; j++)
{
mtx = new double[3,3];
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
mtx[k, l] = Math.Sin(j + (k*3) + l + seed);
}
}
}
}
}
推荐答案
不是导致性能下降的线程.但这是线程本身的创造".
It is not that the threads that causes the performance to go down. But it is the "creation" of the thread itself.
您需要从OS线程池中借用一个已经创建的线程,而不是创建一个全新的线程.使用ThreadPool
类而不是使用new Thread()
Instead of creating a brand new thread, you need to borrow an already created thread form the OS thread pool. Use ThreadPool
class instead of using new Thread()
这篇关于.Net中的多线程性能不佳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!