Skip to content

Instantly share code, notes, and snippets.

@fomkin
Last active June 16, 2016 20:01
Show Gist options
  • Save fomkin/ae2b3661e6915aa6092e44708537224f to your computer and use it in GitHub Desktop.
Save fomkin/ae2b3661e6915aa6092e44708537224f to your computer and use it in GitHub Desktop.
import akka.actor._
object Main extends App {
val N = 2000000
val system = ActorSystem("mySystem")
val input = system.actorOf(Props[Input])
val output = system.actorOf(Props[Output])
val state = system.actorOf(Props(classOf[State], input, output))
class Output extends Actor {
val startTime = System.nanoTime()
def receive: Receive = {
case s: String =>
s.toInt match {
case i if i == N / 10 => println(i)
case i if i == N / 5 => println(i)
case i if i == N / 3 => println(i)
case i if i == N / 2 => println(i)
case i if i == N - N / 3 => println(i)
case i if i == N - N / 5 => println(i)
case i if i == N - N / 10 => println(i)
case i if i == N =>
val t2 = (System.nanoTime() - startTime) / 1000000000d
println(s"Execution time: ${t2}s")
case _ =>
}
}
}
class Input extends Actor {
def receive: Receive = {
case "ready" => sender ! "1"
}
}
class State(input: ActorRef, output: ActorRef) extends Actor {
var x = 0
def receive: Receive = {
case s: String =>
x = x + s.toInt
output ! x.toString
if (x <= N)
input ! "ready"
}
input ! "ready"
}
}
import java.util.concurrent.ConcurrentLinkedQueue
import scala.concurrent.{ExecutionContext, Future, Await}
import scala.concurrent.duration._
object Main extends App {
val N = 10000000
def foo(read: () => Future[String], write: String => Future[Unit])
(implicit topEc: ExecutionContext): Future[Unit] = {
def loop(state: Int): Future[Unit] = {
for {
text <- read()
x = text.toInt
newState = state + x
_ <- write(newState.toString)
_ <- {
if (newState == N) Future.successful(())
else loop(newState)
}
} yield {
()
}
}
loop(0)
}
import scala.concurrent.ExecutionContext.Implicits.global
val f = foo(
read = () => Future.successful("1"),
write = { s =>
s.toInt match {
case i if i == N / 10 => println(i)
case i if i == N / 5 => println(i)
case i if i == N / 3 => println(i)
case i if i == N / 2 => println(i)
case i if i == N - N / 3 => println(i)
case i if i == N - N / 5 => println(i)
case i if i == N - N / 10 => println(i)
case _ =>
}
Future.successful(())
}
)
val t = System.nanoTime()
Await.result(f, 1 hour)
val t2 = (System.nanoTime() - t) / 1000000000d
println(s"Execution time: ${t2}s")
}
import java.util.concurrent.ConcurrentLinkedQueue
class SerialExecutionContext extends ExecutionContext {
val jobs = new ConcurrentLinkedQueue[Runnable]
val thread = new Thread {
override def run() = {
while (true) {
var job = jobs.poll()
if (job != null) {
job.run()
}
}
}
}
def reportFailure(cause: Throwable): Unit = cause.printStackTrace()
def execute(runnable: Runnable): Unit = {
jobs.add(runnable)
}
thread.start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment