我想学习并行编程以加速算法并选择了 Java。
我编写了两个函数来对数组中的 long
整数求和 - 一个简单地遍历数组,第二个 - 将数组分成多个部分并在单独的线程中对各个部分求和。
我预计使用两个线程将速度提高大约 2 倍是合乎逻辑的。然而,我得到的只是 24% 的加速。此外,使用更多线程,与两个线程相比,我没有得到任何改进(可能少于 1%)。我知道应该有线程创建/加入开销,但我想它不应该那么大。
您能否解释一下,我遗漏了什么或代码中的错误在哪里? 这是代码:
import java.util.concurrent.ThreadLocalRandom;
public class ParallelTest {
public static long sum1 (long[] num, int a, int b) {
long r = 0;
while (a < b) {
r += num[a];
++a;
}
return r;
}
public static class SumThread extends Thread {
private long num[];
private long r;
private int a, b;
public SumThread (long[] num, int a, int b) {
super();
this.num = num;
this.a = a;
this.b = b;
}
@Override
public void run () {
r = ParallelTest.sum1(num, a, b);
}
public long getSum () {
return r;
}
}
public static long sum2 (long[] num, int a, int b, int threadCnt) throws InterruptedException {
SumThread[] th = new SumThread[threadCnt];
int i = 0, c = (b - a + threadCnt - 1) / threadCnt;
for (;;) {
int a2 = a + c;
if (a2 > b) {
a2 = b;
}
th[i] = new SumThread(num, a, a2);
th[i].start();
if (a2 == b) {
break;
}
a = a2;
++i;
}
for (i = 0; i < threadCnt; ++i) {
th[i].join();
}
long r = 0;
for (i = 0; i < threadCnt; ++i) {
r += th[i].getSum();
}
return r;
}
public static void main(String[] args) throws InterruptedException {
final int N = 230000000;
long[] num = new long[N];
for (int i = 0; i < N; ++i) {
num[i] = ThreadLocalRandom.current().nextLong(1, 9999);
}
// System.out.println(Runtime.getRuntime().availableProcessors());
long timestamp = System.nanoTime();
System.out.println(sum1(num, 0, num.length));
System.out.println(System.nanoTime() - timestamp);
for (int n = 2; n <= 4; ++n) {
timestamp = System.nanoTime();
System.out.println(sum2(num, 0, num.length, n));
System.out.println(System.nanoTime() - timestamp);
}
}
}
编辑:我有 4 核(8 线程)的 i7 处理器。 代码给出的输出是:
1149914787860
175689196
1149914787860
149224086
1149914787860
147709988
1149914787860
138243999
最佳答案
该程序可能是主内存带宽受限于只有两个线程,因为它是一个小循环,它获取数据的速度几乎与 ram 向处理器提供数据的速度一样快。
关于Java 多线程带来的性能提升非常小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41087630/