Skip to content

Instantly share code, notes, and snippets.

@visualskyrim
Forked from volgar1x/Kernel.scala
Created May 28, 2014 06:24
Show Gist options
  • Save visualskyrim/053501b8e1d3714b6531 to your computer and use it in GitHub Desktop.
Save visualskyrim/053501b8e1d3714b6531 to your computer and use it in GitHub Desktop.
object Kernel {
implicit class Times(val n: Int) extends AnyVal {
def times[T](block: => T) = for (i <- 1 to n) yield block
def times[T](block: Int => T) = for (i <- 1 to n) yield block(i)
}
implicit class RunnableConversion(block: => Unit) extends Runnable {
def run = block
}
case class Hello(name: String)
class WorkerActor extends Actor {
def receive = {
case Hello(name) => {
sender ! s"hello $name from ${self.path}"
}
}
}
class MasterActor(workers: Seq[ActorRef]) extends Actor {
implicit val executionContext = context.dispatcher
def receive = {
case msg => Future.sequence(workers map (_ ? msg)) pipeTo sender
}
}
def bench(requests: Int)(block: => Unit) {
val s = new Stopwatch
println("preparing...")
20000 times block // warm up JIT
println("begin benchmark...")
s.start()
requests times block
s.stop()
println(s"it takes ${s.elapsed(TimeUnit.MICROSECONDS)} µs to handle $requests requests")
println(s"it takes ${s.elapsed(TimeUnit.MICROSECONDS) / requests} µs to handle only one request")
}
implicit val timeout = Timeout(200 millis)
def main(args: Array[String]) {
import scala.concurrent.ExecutionContext.Implicits.global
val nrWorkers = 5
val workers = ActorSystem("workers", ConfigFactory.parseString(
"""
|akka {
| actor.provider = "akka.remote.RemoteActorRefProvider"
|
| remote {
| netty.hostname = "127.0.0.1"
| netty.port = 5556
| }
|}
""".stripMargin))
val master = ActorSystem("master", ConfigFactory.parseString(
"""
|akka {
| actor.provider = "akka.remote.RemoteActorRefProvider"
|
| remote {
| netty.hostname = "127.0.0.1"
| netty.port = 5555
| }
|}
""".stripMargin))
nrWorkers times { i: Int => workers.actorOf(Props[WorkerActor], name = s"worker$i")}
val workerActors = nrWorkers times { i: Int => master.actorFor(s"akka://[email protected]:5556/user/worker$i")}
val masterActor = master.actorOf(Props(new MasterActor(workerActors)))
Thread.sleep(1000)
bench(1000) { Await.result(masterActor ? Hello("world"), 1 second) }
master.shutdown()
workers.shutdown()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment