Advertisement
jules0707

HorizontalBoxBlurRunner

Feb 23rd, 2017
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.21 KB | None | 0 0
  1. package scalashop
  2.  
  3. import org.scalameter._
  4. import common._
  5.  
  6. object HorizontalBoxBlurRunner {
  7.  
  8.   val standardConfig = config(
  9.     Key.exec.minWarmupRuns -> 5,
  10.     Key.exec.maxWarmupRuns -> 10,
  11.     Key.exec.benchRuns -> 10,
  12.     Key.verbose -> true) withWarmer (new Warmer.Default)
  13.  
  14.   def main(args: Array[String]): Unit = {
  15.     val radius = 3
  16.     val width = 1920
  17.     val height = 1080
  18.     val src = new Img(width, height)
  19.     val dst = new Img(width, height)
  20.     val seqtime = standardConfig measure {
  21.       HorizontalBoxBlur.blur(src, dst, 0, height, radius)
  22.     }
  23.     println(s"sequential blur time: $seqtime ms")
  24.  
  25.     val numTasks = 32
  26.     val partime = standardConfig measure {
  27.       HorizontalBoxBlur.parBlur(src, dst, numTasks, radius)
  28.     }
  29.     println(s"fork/join blur time: $partime ms")
  30.     println(s"speedup: ${seqtime / partime}")
  31.   }
  32. }
  33.  
  34. /** A simple, trivially parallelizable computation. */
  35. object HorizontalBoxBlur {
  36.  
  37.   /**
  38.    * Blurs the rows of the source image `src` into the destination image `dst`,
  39.    *  starting with `from` and ending with `end` (non-inclusive).
  40.    *
  41.    *  Within each row, `blur` traverses the pixels by going from left to right.
  42.    */
  43.   def blur(src: Img, dst: Img, from: Int, end: Int, radius: Int): Unit = {
  44.     for (
  45.       y <- from until end;
  46.       x <- 0 until src.width
  47.     ) yield dst.update(x, y, boxBlurKernel(src, x, y, radius))
  48.   }
  49.  
  50.   /**
  51.    * Blurs the rows of the source image in parallel using `numTasks` tasks.
  52.    *
  53.    *  Parallelization is done by stripping the source image `src` into
  54.    *  `numTasks` separate strips, where each strip is composed of some number of
  55.    *  rows.
  56.    */
  57.   def parBlur(src: Img, dst: Img, numTasks: Int, radius: Int): Unit = {
  58.     val stripSize = Math.max(src.height / numTasks, 1)
  59.     val splittingPoints = (0 until src.height) by stripSize
  60.     val startEnd = splittingPoints zip splittingPoints.tail
  61.     val lastStrip = if(startEnd.isEmpty){
  62.       (0,src.height) } else {(startEnd.last._2,src.height)}
  63.  
  64.       val tasks = (startEnd:+lastStrip).map {
  65.       t =>
  66.         {
  67.           task {
  68.             blur(src, dst, t._1, t._2, radius)
  69.           }
  70.         }
  71.     }
  72.     tasks.map { t => t.join() }
  73.    }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement