java stream 并行_java8对stream串、并行流的测试性能的用例

上一篇文章说到,对于在java8中使用stream中的并行流的几个建议的说明。下面我们就写一个测试用例测量一下(在性能优化时,遵循的三个黄金规则:测量、测量、测量)com.kisszero.one.paralleljava.util.stream.LongStreamjava.util.stream.StreamParallelStreamsUtils {

(n) {

result = (i = i <= ni++) {

result += i}

result}

(n) {

Stream.(i -> i + ).limit(n).reduce(Long::).get()}

(n) {

Stream.(i -> i + ).limit(n).parallel().reduce(Long::).get()}

(n) {

LongStream.(n).reduce(Long::).getAsLong()}

(n) {

LongStream.(n).parallel().reduce(Long::).getAsLong()}

(n) {

Accumulator accumulator = Accumulator()LongStream.(n).forEach(accumulator::add)accumulator.}

(n) {

Accumulator accumulator = Accumulator()LongStream.(n).parallel().forEach(accumulator::add)accumulator.}

Accumulator {

= (value) {

+= value}

}

}

com.kisszero.one.paralleljava.util.concurrent.ForkJoinPooljava.util.function.FunctionParallelStreamsTest {

ForkJoinPool = ForkJoinPool()(String[] args) {

System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )System..println(+ (ParallelStreamsUtils::) + )}

<> (Function<> finput) {

fastest = Long.(i = i 

start = System.()result = f.apply(input)duration = (System.() - start) / System..println(+ result)(duration 

fastest}

}

结果:

Iterative Sum done in: 5 msecs

Sequential Sum done in: 154 msecs

Parallel forkJoinSum done in: 376 msecs

Range forkJoinSum done in: 13 msecs

Parallel range forkJoinSum done in: 8 msecs

SideEffect sum done in: 4 msecs

Result: 22454695176953

Result: 20121132009947

Result: 16076928917786

Result: 16957805754284

Result: 13642545729260

Result: 12997343158699

Result: 13761162440338

Result: 17902422526976

Result: 21642228116467

Result: 17496039228969

SideEffect prallel sum done in: 47 msecs

Stream中的LongStream.rangClosed方法比iterate在这种求和的情况下效率更好,因为前者直接产生原始类型的long数字,没有装箱拆箱的开销,还有就是前者生成的数字范围,很容易的拆分为独立的小块。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值