Skip to content

Instantly share code, notes, and snippets.

@cevaris
Created May 23, 2016 22:56
Show Gist options
  • Save cevaris/759a9ffd81ef465dbb6f7132ed8cdc96 to your computer and use it in GitHub Desktop.
Save cevaris/759a9ffd81ef465dbb6f7132ed8cdc96 to your computer and use it in GitHub Desktop.
Some Example formatters and their execution times times
Java Formatter: Elapsed Time: 105ms
Scala Formatter: Elapsed Time: 167ms
BigDecimal Formatter: Elapsed Time: 27ms
Scala custom Formatter: Elapsed Time: 3ms
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