Skip to content

Instantly share code, notes, and snippets.

@japaz
Created November 3, 2011 22:23
Show Gist options
  • Save japaz/1338078 to your computer and use it in GitHub Desktop.
Save japaz/1338078 to your computer and use it in GitHub Desktop.
7L7W Scala - Day 3
// For the sizer program, what would happen if you did not create a
// new actor for each link you wanted to follow?
// An actor must sent more than one message
// What would happen
// to the performance of the application?
// The performace will be worst
// Take the sizer application and add a message to count the number
// of links on the page.
import scala.io._
import scala.actors._
import scala.xml.parsing._
import Actor._
// START:loader
object PageLoader {
def getPageSize(url : String) = Source.fromURL(url).mkString.length
def getNumberOfLinks(url : String) = "<a.*/a>".r.findAllIn(Source.fromURL(url).mkString).size
}
// END:loader
val urls = List("http://www.amazon.com/",
"http://www.twitter.com/",
"http://www.google.com/",
"http://www.cnn.com/" )
// START:time
def timeMethod(method: () => Unit) = {
val start = System.nanoTime
method()
val end = System.nanoTime
println("Method took " + (end - start)/1000000000.0 + " seconds.")
}
// END:time
// START:sequential
def getPageSizeSequentially() = {
for(url <- urls) {
println("Size for " + url + ": " + PageLoader.getPageSize(url) + " links: " + PageLoader.getNumberOfLinks(url))
}
}
// END:sequential
// START:concurrent
def getPageSizeConcurrently() = {
val caller = self
for(url <- urls) {
actor { caller ! (url, PageLoader.getPageSize(url), PageLoader.getNumberOfLinks(url)) }
}
for(i <- 1 to urls.size) {
receive {
case (url, size, links) =>
println("Size for " + url + ": " + size + " links: " + links)
}
}
}
// END:concurrent
// START:script
println("Sequential run:")
timeMethod { getPageSizeSequentially }
println("Concurrent run")
timeMethod { getPageSizeConcurrently }
// END:script
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment