Skip to content

Instantly share code, notes, and snippets.

@asflierl
Created September 9, 2010 22:39
Show Gist options
  • Save asflierl/572725 to your computer and use it in GitHub Desktop.
Save asflierl/572725 to your computer and use it in GitHub Desktop.
object Looping {
val l = 1000
val l2 = l * l
val l3 = l * l * l
def main(args: Array[String]): Unit = {
warmup()
measure()
}
def warmup(): Unit = {
new IntCountUpSum().f(l3)
new LongCountUpSum().f(l3)
// new TwoIntLoops().f(l2, l)
}
def measure(): Unit = {
Timer(new IntCountUpSum().f(l3))
Timer(new LongCountUpSum().f(l3))
// Timer(new TwoIntLoops().f(l2, l))
}
}
class IntCountUpSum {
import For.cfor
def f(n: Int) = {
var sum = 0
cfor[Int](0, _ < n, _ + 1)(i => {
sum += i
})
sum
}
}
class LongCountUpSum {
import For.cfor
def f(n: Long) = {
var sum = 0L
cfor[Long](0L, _ < n, _ + 1L)(i => {
sum += i
})
sum
}
}
class TwoIntLoops {
import For.cfor
def f(n: Int, o: Int) = {
val r = n / math.sqrt(o)
val max = (o * (o + 1) / 2) * (r / 3) / 2
var sum = 0
cfor[Int](0, a => a < r && sum < max, _ + 3)(i => {
cfor[Int](o, _ > 0, _ - 1)(j => {
sum += j
})
})
sum
}
}
object For {
def cfor[@specialized A](zero: A, okay: A => Boolean, inc: A => A)(act: A => Unit) = {
var i = zero
while (okay(i)) {
act(i)
i = inc(i)
}
}
}
object Timer {
import scala.compat.Platform
import java.util.Locale
def apply(functionToMeasure: => Any) : Unit = {
val before = System.nanoTime
val result = functionToMeasure
val after = System.nanoTime
println("Result: " + result.toString)
println("Execution took %.3f ms.".format((after - before).toDouble * 1e-6d))
}
}//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment