gpt4 book ai didi

java - 什么时候 1 个线程比同时运行的多个线程运行得更快

转载 作者:行者123 更新时间:2023-11-29 03:00:16 25 4
gpt4 key购买 nike

对于一项任务,我必须实现一个 Java 程序,该程序在运行多个线程时实际上比仅运行 1 个线程要慢。我知道创建一个线程需要一些开销,但在这个例子中我处理的是一个大数组 20,000x20,000 .没有依赖关系,所以创建 4 个较小的 block 并同时运行它们的好处应该总是超过创建线程的成本,对吧?

for (int i = 0; i < numThreads; i++) {

// for each iteration of the body's for loop,
// calculate the starting and ending indexes
// of the ith chunk of the y dimension of
// the anArray array
final int indexStart = i * chunkSize;
final int indexEnd = (i + 1) * chunkSize;

// each "execute" method of the Executor class
// creates a new object of type Runnable ...
// be careful with the parentheses here ... the
// entire next code block is being passes
// as a parameter to the execute method
ex.execute(new Runnable() {

// The run() method is declared abstract in the Runnable
// class, so it MUST be overriden. The body of the
// run method is the "code" that each thread executes
@Override
public void run() {

for (int j=0; j<anArray.length; j++){
for (int k = indexStart; k < indexEnd; k++){
anArray[j][k] = anArray[j][k] * anArray[j][k] / 3.45 * Math.sqrt(anArray[j][k]);

}

} // end for

} // end run
}
);
}

我们的任务是只修改最里面的 for 循环,我们可以在那里做任何我们想做的事,但是当使用更多线程执行时,它必须使运行时变慢。上限为 8 个线程。我真正的问题是在实现多线程时什么会导致更多的开销。我做了一些研究,发现您可以通过单个线程使用大部分 CPU,因此创建更多线程不会有帮助,这怎么可能。

最佳答案

I have done some research and found that you can use most of the cpu with a single thread so creating more wont help, how is this possible.

多个线程在独立运行时效果最佳。这意味着对共享资源的任何过度使用都会限制甚至降低使用多线程的速度。

假设您有一个 4 核套接字。这意味着您有 4 个内核,每个内核具有 32 KB 的 L1 缓存。如果你使用的内存超过这个数量,他们必须使用 L2 缓存,这会慢 3-4 倍左右。但这些都只有 256 KB 的内存。如果您使用的不止一个,他们必须使用唯一的一个 L3 缓存。即使用超过 1 MB 的内存,您的应用程序将无法再扩展并且速度可能会变慢。

在您的情况下,您还使用了浮点单元 esp Math.sqrt,它占用了相当多的 CPU。每个内核只有一个 FPU,因此您可能会发现使用超线程不会有太大帮助。 (可能 <10%)

简而言之,鉴于您的浮点运算非常昂贵,我希望您应该获得良好的可扩展性,直到您拥有的内核数量为止。随着您获得更多内核,在某些时候您的 L3 缓存将成为瓶颈。例如对于 18 核,您可能会发现这是一个问题。

关于java - 什么时候 1 个线程比同时运行的多个线程运行得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35474677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com