这是顺序版本:
void f(long n) {
for (int i=1; i<n-1; i++) {
// do nothing
}
}
List result = []
(1..99999).each {
f(it)
result << it
}
运行代码需要几秒钟。
void f(long n) {
for (int i=1; i<n-1; i++) {
// do nothing
}
}
withPool {
runForkJoin(1,99999) { a, b ->
List result = []
(a..b).each {
f(it)
result << it
}
return result
}
}
上面的代码需要几分钟才能完成。我还没有调用任何 forkOffChild()
或 childrenResults()
。我在 Windows 和具有 Intel 超线程(2 个逻辑 CPU)的单核 CPU 中运行此代码。 Java Runtime.runtime.availableProcessors()
返回 2。
我不明白为什么使用 runForkJoin
的代码比顺序代码慢得多(分钟与秒)。
最佳答案
runForJoin() 方法对代码片段中的性能没有影响。正是 withPool() 方法导致速度变慢。这是因为 withPool() 方法向 Groovy 对象的动态作用域添加了多个 xxxParallel() 方法,从而减慢了方法解析速度。
将 f() 方法注释为 @CompileStatic 将为您提供预期的性能。
关于java - 为什么即使没有 forkOffChild(),GPars runForkJoin 也很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23711224/