Skip to content

Instantly share code, notes, and snippets.

@akehoyayoi
Created March 11, 2017 02:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akehoyayoi/fbf54335e99f55fc9da637a7bbb576f8 to your computer and use it in GitHub Desktop.
Save akehoyayoi/fbf54335e99f55fc9da637a7bbb576f8 to your computer and use it in GitHub Desktop.
Fibonacci Test
import scala.collection.mutable
/**
* Created by okayayohei on 2017/03/11.
*/
object Main {
trait Fib {
def fib(n: Long): Long
}
object Normal extends Fib {
def fib(n: Long): Long = {
if(n <= 2) 1
else fib(n - 1) + fib(n - 2)
}
}
object CallOnce extends Fib {
def fibLocal(a: Long, b: Long, c: Long): Long = {
if(c <= 2) a
else fibLocal(a + b, a, c - 1)
}
def fib(n: Long) = {
fibLocal(1, 1, n)
}
}
object Cache extends Fib {
var cache: mutable.Map[Long, Long] = scala.collection.mutable.Map.empty[Long, Long]
def fib(n: Long) = {
cache.getOrElseUpdate(n, {
if(n <= 2) 1
else fib(n - 1) + fib(n - 2)
})
}
}
object CacheAndCallOnce extends Fib {
var cache: mutable.Map[Long, Long] = scala.collection.mutable.Map.empty[Long, Long]
def fibLocal(a: Long, b: Long, c: Long): Long = {
if(c <= 2) a
else fibLocal(a + b, a, c - 1)
}
def fib(n: Long) = {
cache.getOrElseUpdate(n, {
fibLocal(1, 1, n)
})
}
}
def main(args: Array[String]): Unit = {
val n: Long = 50
printExecutionTime {
println("----Normal----")
println(Normal.fib(n))
}
printExecutionTime {
println("----CallOnce----")
println(CallOnce.fib(n))
}
printExecutionTime {
println("----Cache----")
println(Cache.fib(n))
}
printExecutionTime {
println("----Cache----")
println(Cache.fib(n))
}
printExecutionTime {
println("----CacheAndCallOnce----")
println(CacheAndCallOnce.fib(n))
}
printExecutionTime {
println("----CacheAndCallOnce----")
println(CacheAndCallOnce.fib(n))
}
}
/** 引数の処理の実行時間を表示 */
def printExecutionTime(proc: => Unit) = {
val start = System.currentTimeMillis
proc
println((System.currentTimeMillis - start) + "msec")
}
}
@akehoyayoi
Copy link
Author

[info] Running Main 
----Normal----
12586269025
55601msec
----CallOnce----
12586269025
15msec
----Cache----
12586269025
37msec
----Cache----
12586269025
0msec
----CacheAndCallOnce----
12586269025
3msec
----CacheAndCallOnce----
12586269025
0msec
[success] Total time: 63 s, completed 2017/03/11 11:55:16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment