一、Stream并行计算体验,利用多核加快计算速度

stream的并发,多个cpu执行同一个任务,提高效率;

需求:从1+...+10000000,看下各种计算方法的运行时间是多少

代码例子如下:

 package com.cy.java8;

 import java.util.function.Function;
import java.util.stream.LongStream;
import java.util.stream.Stream; public class ParallelProcessing { public static void main(String[] args) {
//查看计算机核心线程数
//System.out.println(Runtime.getRuntime().availableProcessors()); long fastest1 = measureSumPerformance(ParallelProcessing::normalAdd, 10000000);
System.out.println("normalAdd the best processing time : " + fastest1 + " ms"); long fastest2 = measureSumPerformance(ParallelProcessing::iterateStream, 10000000);
System.out.println("iterateStream the best processing time : " + fastest2 + " ms"); long fastest3 = measureSumPerformance(ParallelProcessing::parallelStream, 10000000);
System.out.println("parallelStream the best processing time : " + fastest3 + " ms"); long fastest4 = measureSumPerformance(ParallelProcessing::parallelStream2, 10000000);
System.out.println("parallelStream2 the best processing time : " + fastest4 + " ms"); long fastest5 = measureSumPerformance(ParallelProcessing::parallelStream3, 10000000);
System.out.println("parallelStream3 the best processing time : " + fastest5 + " ms"); } /**
* 将下面的求和方法分别计算10次,取10次中运行最短的时间
*/
private static long measureSumPerformance(Function<Long, Long> adder, long limit){
long fastest = Long.MAX_VALUE; for(int i=0; i<10; i++){
long startTime = System.currentTimeMillis();
long result = adder.apply(limit);
long spendTime = System.currentTimeMillis() - startTime;
System.out.println("the sum result is " + result);
if(spendTime < fastest){
fastest = spendTime;
}
}
return fastest;
} /**
* 计算一串long类型的总和,普通的stream
* @param limit
* @return
*/
private static long iterateStream(long limit){
return Stream.iterate(1L, i->i+1).limit(limit).reduce(0L, Long::sum);
} /**
* 使用Stream.parallel
* 比较慢,为什么?
* Stream.iterate不适合并行计算
*/
private static long parallelStream(long limit){
return Stream.iterate(1L, i->i+1).parallel().limit(limit).reduce(0L, Long::sum);
} /**
* 将上面的Stream先自动拆箱为long,再并行
* 虽然拆箱为LongStream,还是很慢,为什么?
* Stream.iterate不适合并行计算
*/
private static long parallelStream2(long limit){
return Stream.iterate(1L, i -> i + 1)
.mapToLong(Long::longValue)
.parallel().limit(limit).reduce(0L, Long::sum);
} /**
* 使用LongStream.range
* 很快,比normalAdd快了近一倍,为什么?
* LongStream、IntStream等..它们的IntStream.range非常卓越的适合并行计算
*/
private static long parallelStream3(long limit){
return LongStream.rangeClosed(1, limit).parallel().reduce(0L, Long::sum);
} /**
* 以前的写法
* @param limit
* @return
*/
private static long normalAdd(long limit){
long result = 0L;
for(long i=0L; i <= limit; i++){
result += i;
}
return result;
}
}

console:

the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
normalAdd the best processing time : 3 ms
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
iterateStream the best processing time : 78 ms
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
parallelStream the best processing time : 128 ms
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
parallelStream2 the best processing time : 178 ms
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
the sum result is 50000005000000
parallelStream3 the best processing time : 0 ms

结论:不一定是所有的方法产生的Stream都适合于并行的方式去做的,一定要注意有些方法是对于并行是厌恶的,有些方法是喜欢并行的;

列举一些例子如下:

数据源           分解性能
Source           Decomposability
ArrayList           Excellent
LinkedList           Poor
IntStream.range        Excellent
Stream.iterate         Poor
HashSet             Good
TreeSet              Good

----

Stream的并行计算的更多相关文章

  1. java8Stream原理深度解析

    Java8 Stream原理深度解析 Author:Dorae Date:2017年11月2日19:10:39 转载请注明出处 上一篇文章中简要介绍了Java8的函数式编程,而在Java8中另外一个比 ...

  2. SQL Server-聚焦查询计划Stream Aggregate VS Hash Match Aggregate(二十)

    前言 之前系列中在查询计划中一直出现Stream Aggregate,当时也只是做了基本了解,对于查询计划中出现的操作,我们都需要去详细研究下,只有这样才能对查询计划执行的每一步操作都了如指掌,所以才 ...

  3. Java 使用 Stream API 筛选 List

    前言 上课的时候看到老师用迭代器来遍历 List 中的元素的时候,我的内心是极其嫌弃的,这种迭代方法不能直接访问当前的元素,而且写起来也麻烦.于是上网查了查 Java 有没有类似于 Linq 的东西, ...

  4. Java Stream 使用详解

    Stream是 Java 8新增加的类,用来补充集合类. Stream代表数据流,流中的数据元素的数量可能是有限的,也可能是无限的. Stream和其它集合类的区别在于:其它集合类主要关注与有限数量的 ...

  5. baike并行计算概念

    并行计算 概论 ▪ 高性能计算 ▪ 计算机集群 ▪ 分布式计算 ▪ 网格计算 ▪ 云端运算         方式 ▪ Bit-level parallelism ▪ Instruction level ...

  6. [Java 8 Lambda] java.util.stream 简单介绍

    包结构例如以下所看到的: 这个包的结构非常easy,类型也不多. BaseStream接口 全部Stream接口类型的父接口,它继承自AutoClosable接口,定义了一些全部Stream都具备的行 ...

  7. Java8 Stream简介

    Stream是Java 8新增的重要特性, 它提供函数式编程支持并允许以管道方式操作集合. 流操作会遍历数据源, 使用管道式操作处理数据后生成结果集合, 这个过程通常不会对数据源造成影响. lambd ...

  8. [三]java8 函数式编程Stream 概念深入理解 Stream 运行原理 Stream设计思路

    Stream的概念定义   官方文档是永远的圣经~     表格内容来自https://docs.oracle.com/javase/8/docs/api/   Package java.util.s ...

  9. [零]java8 函数式编程入门官方文档中文版 java.util.stream 中文版 流处理的相关概念

    前言 本文为java.util.stream 包文档的译文 极其个别部分可能为了更好理解,陈述略有改动,与原文几乎一致 原文可参考在线API文档 https://docs.oracle.com/jav ...

随机推荐

  1. CSS的四种定位的参照物

    一.static定位 HTML 元素的默认值,即没有定位,遵循正常的文档流对象. 静态定位的元素不会受到 top, bottom, left, right影响. <!DOCTYPE html&g ...

  2. time、date、datetime、timestamp和year

    在此声明mysql数据库 时间上总共有五中表示方法:它们分别是 time.date.datetime.timestamp和year. time : “hh:mm:ss”格式表示的时间值,格式显示TIM ...

  3. Java日志打印方法

    一.使用log4j打印日志 1. 下载log4j.jar和commons-logging.jar.     log4j.jar下载地址:http://logging.apache.org/log4j/ ...

  4. Linux查看某进程的线程

    首先得知道你要查的进程的PID: 比如我要查看看我unimrcpserver的线程 第二种方法:top top命令可以实时显示各线程情况.就相当于windows的资源管理器.

  5. 清楚webView的缓存

    +(void)clearCache{    NSHTTPCookie *cookie;    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage s ...

  6. 聚合函数 Aggregate Function

    聚合函数是用来统计每个分组的统计信息,它们要跟 group by 一起使用,用来将每个分组所有数据 聚合 成一条统计数据. 包括 max/min/count/avg/sum 等. -- 按照部门进行分 ...

  7. JAVA笔记26-网络编程(不等于网站编程)

    一.网络基础(TCP/IP详解) 1.IP协议(Internet Protocol):网络层,支持网间数据报通信.无连接数据报传送,数据报路由选择和差错控制. IPv4 32位(4字节),IPv6 1 ...

  8. 算法——得到数据流中前K大的数

    用优先队列 public PriorityQueue<Integer> kthLargest(int k, int[]a) { PriorityQueue<Integer> q ...

  9. 第九周作业—N42-虚怀若谷

    一.编写脚本,接收二个位置参数,magedu和/www,判断系统是否有magedu,如果没有则自动创建magedu用户,并自动设置家目录为/www [root@centos7 data]# cat u ...

  10. 为什么second是秒也是第二?

    起源 早期在西方,一小时分为 60 分钟.后来,科学发达了.文明进步了,人们认为一分钟太粗放了.必须划分得更细致,于是就把一分钟划分成 60 等分.由于是对时间的第二次划分,就将新的 60 等分的“单 ...