本文介绍了为什么IntStream.range(0,100000).parallel.foreach需要比循环更长的正常时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习Java中的Streams和parallel并且我想知道为什么正常的for循环花费的时间比 IntStream 更少的时间与向数组添加项目并行。

I am just starting to learn about the Streams and parallel in Java and I was wondering why a normal for loop takes less time than IntStream paralleled at adding items to an array.

package parallel;

import java.util.stream.IntStream;

public class Parallel {

    public static void main(String[] args) {
         final int[] intArray = new int[100000];
        long startTime = System.currentTimeMillis(); 
        IntStream.range(0, 100000).parallel().forEach(i ->  intArray[i]=i);
        long endTime = System.currentTimeMillis();
        System.out.println("Parallel time: " + (endTime-startTime));
        final int[] intArray2 = new int[100000];
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        startTime = System.currentTimeMillis();
        for(int i = 0; i < 100000; i++){
            intArray2[i] = i;
        }
        endTime = System.currentTimeMillis();
        System.out.println("Non parallel time: " + (endTime-startTime));
    }
}

获得这样的结果。

平行时间:110

非平行时间:7

推荐答案

您为每个元素执行的操作非常简单,它只是一个赋值,非常快。在并行版本中,启动处理操作的多个线程会产生大量开销。单独使用此操作可能比非平行操作所需的时间更长。

The operation you perform for each element is very simple, it's just an assignment, which is very fast. In the parallel version, you have a lot of overhead by starting the multiple threads that handle the operations. This alone will likely already take longer than what the very simple operation takes when applied non-parallel.

此外,在非并行版本中,值非常线性地写入对于数组,对于许多CPU来说是最佳行为。在并行版本中,你可能会遇到冲突,因为每个线程都试图写入同一个数组(虽然在不同的位置,但可能仍然在同一个缓存行上),并且当几个线程访问数组的不同部分时,你可能还会出现缓存未命中,从而降低速度。

Also, in the non-parallel version, the values are written very linearly to the array, for many CPUs an optimal behaviour. In the parallel version though, you'll might get conflicts as each thread tries to write to the same array (although on different positions, but probably still on the same cache line), and as several threads access different parts of the array, you might also get cache misses which slow things down.

随着运营成本的增加,并行版本的开销与总成本相比变得更小,最终导致比非并行情况更快的执行。

With a more expensive operation, the overhead of the parallel version becomes smaller compared to the total costs, which will in the end result in faster execution than the non-parallel case.

这篇关于为什么IntStream.range(0,100000).parallel.foreach需要比循环更长的正常时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 00:10