开了并行需要17秒左右,把.parallel()去掉后只用5秒左右(i5双核)
public static void main(String[] args)
{
long start = System.currentTimeMillis();
long ret = new Random().longs(0, 10)
.limit(10000 * 10000)
.parallel()
.sum();
long end = System.currentTimeMillis();
System.out.println(ret);
System.out.println("takes " + (end - start) + "ms");
}
}
然后把代码中的stream改成用range而不用random生成随机数流,则是开并行要比不开并行快一倍(300ms:600ms):
public static void main(String[] args)
{
long start = System.currentTimeMillis();
long ret = IntStream.range(0, 1000000000)
.parallel()
.sum();
long end = System.currentTimeMillis();
System.out.println(ret);
System.out.println("takes " + (end - start) + "ms");
}
}
为什么前一个例子开并行会更慢,是random类的缘故吗?望指教!
After turning on parallelism, the original array needs to be divided into blocks, accumulated in each block, and then merged. These additional operations take time. The accumulation itself is a very efficient linear operation. Therefore, if the parallel data is not large enough, or the parameters (such as the number of tasks, etc.) are set unreasonably, the efficiency will not be as high as before