Skip to content

Instantly share code, notes, and snippets.

@klaeufer
Last active December 1, 2021 01:25
Show Gist options
  • Save klaeufer/5409687 to your computer and use it in GitHub Desktop.
Save klaeufer/5409687 to your computer and use it in GitHub Desktop.
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 p1 = new java.lang.Thread { override def run() = { isPrime(1500450271) } }
val p2 = new java.lang.Thread { override def run() = { isPrime(1500450271) } }
val t0 = System.currentTimeMillis
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