Last active
August 29, 2015 14:05
-
-
Save trylks/6b20d4466643855b4052 to your computer and use it in GitHub Desktop.
A gist for this question: http://stackoverflow.com/questions/25276990/making-map-concurrent-implicitly
This file contains 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
package main | |
import scala.concurrent._ | |
import ExecutionContext.Implicits.global | |
import scala.concurrent.duration.Duration | |
object NCApp { | |
def main(args: Array[String]) = { | |
val l = 1 to 100 | |
var start = now() | |
val zero = l.map(toFuture(delay)).iterator.map(futurize(slowmore)).map(fromFuture(x => x)).fold(1)(checkOp) | |
println(s"zero took: ${now() - start}, the result is: $zero") | |
start = now() | |
val one = l.par.map(delay).map(slowmore).seq.fold(1)(checkOp) | |
println(s"one took: ${now() - start}, the result is: $one") | |
start = now() | |
val anotherone = l.par.map(delay).iterator.map(slowmore).seq.fold(1)(checkOp) | |
println(s"anotherone took: ${now() - start}, the result is: $anotherone") | |
start = now() | |
val yetanotherone = l.par.iterator.map(delay).map(slowmore).seq.fold(1)(checkOp) | |
println(s"yetanotherone took: ${now() - start}, the result is: $yetanotherone") | |
start = now() | |
val two = l.map(toFuture(delay)).iterator.map(fromFuture(slowmore)).fold(1)(checkOp) | |
println(s"two took: ${now() - start}, the result is: $two") | |
start = now() | |
val three = cmap(l, delay).map(slowmore).fold(1)(checkOp) | |
println(s"three took: ${now() - start}, the result is: $three") | |
start = now() | |
val four = cmapi(l.iterator, delay).map(slowmore).fold(1)(checkOp) | |
println(s"four took: ${now() - start}, the result is: $four") | |
} | |
def cmapi[I, O](t: Iterator[I], f: I => O) = { (t.map(x => future { f(x) })).map(Await.result(_, Duration.Inf)) } | |
def cmap[I, O](t: TraversableOnce[I], f: I => O) = { (t.map(x => future { f(x) })).map(Await.result(_, Duration.Inf)) } | |
def now() = System.currentTimeMillis() | |
def delay(i: Int): Int = { | |
Thread sleep 9000 | |
i * 2 | |
} | |
def futurize[A, B](f: A => B): Future[A] => Future[B] = toFuture(fromFuture(f)) | |
def toFuture[A, B](f: A => B): A => Future[B] = x => future { f(x) } | |
def fromFuture[A, B](f: A => B): Future[A] => B = x => f(Await.result(x, Duration.Inf)) | |
def slowmore(i: Int): Int = { | |
Thread sleep 1000 | |
i / 2 | |
} | |
def checkOp(a: Int, b: Int): Int = a % b + 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment