与withPool并行

use*_*330 2 parallel-processing concurrency groovy gpars

我找到了一个如何使用的例子withPool.它说我只需要将这个词添加Parallel到Groovy的方法中,比如说collect, find, each,将它放入withPool并执行代码并行.

import static groovyx.gpars.GParsPool.withPool

list = 1..1000000

withPool{
    squares = list.collectParallel { it * it}
}
println squares
Run Code Online (Sandbox Code Playgroud)

有没有机会检查它是否真的平行?
我尝试使用相同的代码进行基准测试,但顺序方式
和并行方式要慢得多.

tim*_*tes 6

不确定你的意思'但顺序和平行的方式要慢得多' ......

这将并行运行,但是对于这个简单的示例,将作业发送到其他处理器并处理结果排序的额外成本可能最终花费的时间超过仅仅增加一些数字

有关显示其工作的简单示例,您可以执行以下操作:

import static groovyx.gpars.GParsPool.withPool

list = [ 2, 2, 2, 2, 2 ]

withPool{
    result = list.collectParallel {
        Thread.sleep( it * 1000 )
        it
    }
}
println result
Run Code Online (Sandbox Code Playgroud)

所以结果应该是[2,2,2,2,2],但collectParallel应该在不到10秒的时间内完成你对串行collect版本的期望

显然这取决于你有多个核心;-)