import java.util.concurrent.{Executors, TimeUnit}
import scala.annotation.tailrec
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.util.{Failure, Success}
object Fact extends App {
def time[R](block: => R): Long = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
val t: Long = TimeUnit.SECONDS.convert((t1 - t0), TimeUnit.NANOSECONDS)
//println(
// "Time taken seconds: " + t)
t
}
def factorial(n: BigInt): BigInt = {
@tailrec
def process(n: BigInt, acc: BigInt): BigInt = {
//println(acc)
if (n <= 0) acc
else process(n - 1, n * acc)
}
process(n, 1)
}
implicit val ec =
ExecutionContext.fromExecutor(Executors.newFixedThreadPool(2))
val f1: Future[Stream[Long]] =
Future.sequence(
(1 to 50).toStream.map(x => Future { time(factorial(100000)) }))
f1.onComplete {
case Success(s) => {
println("Success : " + s.foldLeft(0L)(_ + _) + " seconds!")
}
case Failure(f) => println("Fails " + f)
}
import scala.concurrent.duration._
Await.ready(Future { 10 }, 10000 minutes)
}
我有上面的 Factorial 代码,需要使用多个内核来更快地完成程序,并且应该使用更多的内核。
所以我改变,
Executors.newFixedThreadPool(1) 使用 1 个内核
Executors.newFixedThreadPool(2) 使用 2 个内核
当更改为1 个核心时,结果会在127 秒内出现。但是当更改为2 个内核时,我得到157 秒。
我的疑问是,当我增加内核(并行性)时,它应该会提供良好的性能。但事实并非如此。为什么?
如果我错了或遗漏了什么,请纠正我。
提前致谢。
你是如何测量时间的?您打印出的结果不是执行所花费的时间,而是每个单独调用的时间总和。
Fact.time(Fact.main(Array.empty))
在 REPL 中运行我分别得到 90 和 178 两个线程和一个线程。好像有点道理……
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句