parallelStream

win + R
運行 dxdiag 命令

在這裏插入圖片描述
我的電腦是四核cpu

public class 阿薩德 {
    public static void main(String[] args) {
        int i = Runtime.getRuntime().availableProcessors();
        System.out.println(i); //4
    }
}
public class ParallelProcessing {

    public static void main(String[] args) {


    System.out.println("The best process time(normalAdd)=>" +
            measureSumPerformance(ParallelProcessing::normalAdd, 100_000_000) + " MS");
    //The best process time(normalAdd)=>37 MS

    System.out.println("The best process time(iterateStream)=>" +
            measureSumPerformance(ParallelProcessing::iterateStream, 100_000_000) + " MS");
    //The best process time(iterateStream)=>934 MS


//    System.out.println("The best process time(parallelStream)=>" +
//            measureSumPerformance(ParallelProcessing::parallelStream, 100_000_000) + " MS");
    //The best process time(parallelStream)=>22169 MS

    System.out.println("The best process time(parallelStream2)=>" +
            measureSumPerformance(ParallelProcessing::parallelStream2, 100_000_000) + " MS");
    //The best process time(parallelStream2)=>1519 MS

    System.out.println("The best process time(parallelStream3)=>" +
        measureSumPerformance(ParallelProcessing::parallelStream3, 100_000_000) + " MS");
    //The best process time(parallelStream3)=>13 MS


    }



    private static long measureSumPerformance(Function<Long, Long> adder, long limit) {
        long fastest = Long.MAX_VALUE;
        for (int i = 0; i < 10; i++) {
            long startTimestamp = System.currentTimeMillis();
            long result = adder.apply(limit);
            long duration = System.currentTimeMillis() - startTimestamp;
            System.out.println("The result of sum=>" + result);
            if (duration < fastest) {fastest = duration;}
        }

        return fastest;
    }


    private static long normalAdd(long limit) {
        long result = 0L;
        for (long i = 1L; i < limit; i++) {
            result += i;
        }
        return result;
    }


    private static long iterateStream(long limit) {
        return Stream.iterate(1L, i -> i + 1)
                .limit(limit).reduce(0L, Long::sum);
    }

    /**
     * 以爲需要拆箱裝箱所以有些慢
     * Stream<Long> iterate = Stream.iterate(1L, i -> i + 1);
     * @param limit
     * @return
     */
    private static long parallelStream(long limit) {
        return Stream.iterate(1L, i -> i + 1).parallel()
                .limit(limit).reduce(0L, Long::sum);
    }
    private static long parallelStream2(long limit) {
        return Stream.iterate(1L, i -> i + 1).mapToLong(Long::longValue).parallel()
                .limit(limit).reduce(0L, Long::sum);
    }

    private static long parallelStream3(long limit) {
        return LongStream.rangeClosed(1, limit).parallel().reduce(0L, Long::sum);
    }



}

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章