-
-
Save japaz/1338078 to your computer and use it in GitHub Desktop.
7L7W Scala - Day 3
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
// 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 |
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
// 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