Last active
August 29, 2015 14:02
-
-
Save lpiepiora/80593e34c547186a7ebb to your computer and use it in GitHub Desktop.
scalania18.scala
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
def mostCommon(l: ParSeq[Int]): Int = { | |
def map(acc: Map[Int, Int], el: Int) = acc.updated(el, acc.getOrElse(el, 0) + 1) | |
def reduce(accA: Map[Int, Int], accB: Map[Int, Int]) = accA ++ accB.map { case (k, v) => k -> (v + accA.getOrElse(k, 0)) } | |
l.aggregate(Map[Int, Int]())(map, reduce).maxBy(_._2)._1 | |
} | |
List of 1000000 elements | |
Sequential time: 923 milliseconds | |
Parallel time: 217 milliseconds | |
Threads 1 2 3 4 | |
Times: 252 milliseconds 229 milliseconds 221 milliseconds 212 milliseconds | |
Speed-up 3.488095238095238 3.8384279475982535 3.97737556561086 4.14622641509434 | |
//---------------------------------------------------------------------------------- | |
def decode(l: ParSeq[(Int, Symbol)]): ParSeq[Symbol] = { | |
l.flatMap { case (times, symbol) => List.fill(times)(symbol) } | |
} | |
List of 1000000 elements | |
Sequential time: 769 milliseconds | |
Parallel time: 223 milliseconds | |
Threads 1 2 3 4 | |
Times: 221 milliseconds 195 milliseconds 193 milliseconds 184 milliseconds | |
Speed-up 4.0588235294117645 4.6 4.647668393782383 4.875 | |
// --------------------------------------------------------------------------- | |
def third(col: ParSeq[Int]): Int = { | |
def trippleGenerator(set: TreeSet[Int], x: Int) = (set + x).take(3) | |
def trippleAggregator(setA: TreeSet[Int], setB: TreeSet[Int]) = (setA ++ setB).take(3) | |
col.aggregate(TreeSet[Int]()(Ordering[Int].reverse))(trippleGenerator, trippleAggregator).last | |
} | |
> exercises/testOnly *Ex1ThirdElement* | |
List of 5000000 elements | |
Sequential time: 424 milliseconds | |
Parallel time: 254 milliseconds | |
Threads 1 2 3 4 | |
Times: 283 milliseconds 281 milliseconds 296 milliseconds 302 milliseconds | |
Speed-up 0.5618374558303887 0.5658362989323843 0.5371621621621622 0.5264900662251656 | |
// atomic reference implementation | |
// | |
// | |
def third(col: ParSeq[Int]): Int = { | |
import java.util.concurrent.atomic.AtomicReference | |
val resultSet = new AtomicReference[TreeSet[Int]](TreeSet[Int]()(Ordering[Int].reverse)) | |
def compareAndSet(update: TreeSet[Int] => TreeSet[Int]): Unit = { | |
val oldSet = resultSet.get | |
val newSet = update(oldSet) | |
if (oldSet != newSet && !resultSet.compareAndSet(oldSet, newSet)) compareAndSet(update) | |
} | |
col.foreach { el => | |
compareAndSet(oldSet => (oldSet + el).take(3)) | |
} | |
resultSet.get.last | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment