Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
CPU-bound tasks for experimenting in the Scala REPL
// a CPU-intensive task
def isPrime(i: Long): Boolean = {
if (i == 2) return true
if (i < 2 || i % 2 == 0) return false
var k = 3L
val half = i / 2
while (k <= half) {
if (i % k == 0) return false
k += 2
}
true
}
// running two tasks sequentially
// about 18 seconds on a MacBook Air
val t0 = System.currentTimeMillis
isPrime(1500450271)
isPrime(1500450271)
System.currentTimeMillis - t0
// running two tasks concurrently
// about 12 seconds on a MacBook Air
val t0 = System.currentTimeMillis
val p1 = new java.lang.Thread { override def run() { isPrime(1500450271) } }
val p2 = new java.lang.Thread { override def run() { isPrime(1500450271) } }
p1.start()
p2.start()
p1.join()
p2.join()
System.currentTimeMillis - t0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment