Created
May 23, 2016 22:56
-
-
Save cevaris/759a9ffd81ef465dbb6f7132ed8cdc96 to your computer and use it in GitHub Desktop.
Some Example formatters and their execution times times
This file contains hidden or 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
Java Formatter: Elapsed Time: 105ms | |
Scala Formatter: Elapsed Time: 167ms | |
BigDecimal Formatter: Elapsed Time: 27ms | |
Scala custom Formatter: Elapsed Time: 3ms |
This file contains hidden or 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
object TestFormatters { | |
val r = scala.util.Random | |
def textFormatter(x: Double) = new java.text.DecimalFormat("0.##").format(x) | |
def scalaFormatter(x: Double) = "$pi%1.2f".format(x) | |
def bigDecimalFormatter(x: Double) = BigDecimal(x).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble | |
def scalaCustom(x: Double) = { | |
val roundBy = 2 | |
val w = math.pow(10, roundBy) | |
(x * w).toLong.toDouble / w | |
} | |
def timed(f: => Unit) = { | |
val start = System.currentTimeMillis() | |
f | |
val end = System.currentTimeMillis() | |
println("Elapsed Time: " + (end - start) + "ms") | |
} | |
def main(args: Array[String]): Unit = { | |
print("Java Formatter: ") | |
val iters = 10000 | |
timed { | |
(0 until iters) foreach { _ => | |
textFormatter(r.nextDouble()) | |
} | |
} | |
print("Scala Formatter: ") | |
timed { | |
(0 until iters) foreach { _ => | |
scalaFormatter(r.nextDouble()) | |
} | |
} | |
print("BigDecimal Formatter: ") | |
timed { | |
(0 until iters) foreach { _ => | |
bigDecimalFormatter(r.nextDouble()) | |
} | |
} | |
print("Scala custom Formatter: ") | |
timed { | |
(0 until iters) foreach { _ => | |
scalaCustom(r.nextDouble()) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment