Skip to content

Commit

Permalink
Add mergeSort benchmark to tupleOps.scala
Browse files Browse the repository at this point in the history
  • Loading branch information
Antoine Brunner committed Dec 12, 2019
1 parent 34adaad commit 4fad817
Showing 1 changed file with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package dotty.tools.benchmarks.tuples

import org.openjdk.jmh.annotations._
import scala.util.Random

@State(Scope.Thread)
class TupleOps {
var tuple1: Tuple = _
var tuple2: Tuple = _
var tuple3: Tuple = _

@Setup
def setup(): Unit = {
Expand All @@ -16,6 +18,8 @@ class TupleOps {
tuple2 = ()
for (i <- 1 until 10)
tuple2 = s"elem$i" *: tuple2

tuple3 = Tuple.fromArray(Random.shuffle(1 to 15).toArray)
}

def tupleFlatMap(tuple: Tuple, f: [A] => A => Tuple): Tuple = {
Expand All @@ -34,6 +38,22 @@ class TupleOps {
tailRecReverse(tuple, ())
}

def tupleMerge(tuple1: Tuple, tuple2: Tuple): Tuple = (tuple1, tuple2) match {
case (_, ()) => tuple1
case ((), _) => tuple2
case (x *: xs, y *: ys) =>
if (x.asInstanceOf[Int] <= y.asInstanceOf[Int]) x *: tupleMerge(xs, tuple2)
else y *: tupleMerge(tuple1, ys)
}

def tupleMergeSort(tuple: Tuple): Tuple =
if (tuple.size <= 1) tuple
else {
val (tuple1, tuple2) = tuple.splitAt(tuple.size / 2)
val (sorted1, sorted2) = (tupleMergeSort(tuple1), tupleMergeSort(tuple2))
tupleMerge(sorted1, sorted2)
}

@Benchmark
def reverse(): Tuple = {
tupleReverse(tuple1)
Expand All @@ -43,4 +63,9 @@ class TupleOps {
def flatMap(): Tuple = {
tupleFlatMap(tuple2, [A] => (x: A) => (x, x))
}

@Benchmark
def mergeSort(): Tuple = {
tupleMergeSort(tuple3)
}
}

0 comments on commit 4fad817

Please sign in to comment.