Created
March 11, 2017 02:56
-
-
Save akehoyayoi/fbf54335e99f55fc9da637a7bbb576f8 to your computer and use it in GitHub Desktop.
Fibonacci Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} | |
} |
Author
akehoyayoi
commented
Mar 11, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment