Skip to content

Instantly share code, notes, and snippets.

@mcroydon
Created February 14, 2011 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcroydon/825919 to your computer and use it in GitHub Desktop.
Save mcroydon/825919 to your computer and use it in GitHub Desktop.
Looking at the Actor tax for simple I/O bound operations. With actors it takes ~1000ms. Without it takes ~450ms.
package com.postneo
package toys
package charcount
import scala.actors.Actor
import scala.actors.Actor._
import scala.io.Source
// Iterate over lines in a file, summing the total.
object CharCount {
def main(args: Array[String]) = {
var totalChars: Int = 0
val startTime = System.currentTimeMillis
for (line <- Source.fromFile("/usr/share/dict/words").getLines) totalChars += line.length
println(totalChars + " chars total")
println(System.currentTimeMillis - startTime + "ms")
}
}
// Classes used for messaging to the actor
case class Line(line: String)
case class Stop(startTime: Long)
// An actor that reacts to either Line or Stop messages, summing the total as it goes.
class Counter extends Actor {
var totalChars:Int = 0
def act() {
loop {
react {
case s:Line => {
totalChars += s.line.length
}
case s:Stop => {
println(totalChars + " chars total")
println(System.currentTimeMillis - s.startTime + "ms")
exit()
}
}
}
}
}
// Iterate over lines in a file and send messages to an actor for totaling.
object ActorCharCount {
var counter: Counter = new Counter
def main(args: Array[String]) = {
val startTime = System.currentTimeMillis
counter.start
for (line <- Source.fromFile("/usr/share/dict/words").getLines) counter ! Line(line)
counter ! Stop(System.currentTimeMillis)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment