Skip to content

Commit

Permalink
Add AtomicCell benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
BalmungSan committed Feb 5, 2023
1 parent 6160f7b commit 6c070e1
Showing 1 changed file with 69 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cats.effect.benchmarks

import cats.effect.IO
import cats.effect.std._
import cats.effect.unsafe.implicits.global
import cats.syntax.all._

import org.openjdk.jmh.annotations._

import java.util.concurrent.TimeUnit

/**
* To do comparative benchmarks between versions:
*
* benchmarks/run-benchmark AtomicCellBenchmark
*
* This will generate results in `benchmarks/results`.
*
* Or to run the benchmark from within sbt:
*
* Jmh / run -i 10 -wi 10 -f 2 -t 1 cats.effect.benchmarks.AtomicCellBenchmark
*
* Which means "10 iterations", "10 warm-up iterations", "2 forks", "1 thread". Please note that
* benchmarks should be usually executed at least in 10 iterations (as a rule of thumb), but
* more is better.
*/
@State(Scope.Thread)
@BenchmarkMode(Array(Mode.Throughput))
@OutputTimeUnit(TimeUnit.SECONDS)
class AtomicCellBenchmark {
@Param(Array("1000"))
var size: Int = _

@Param(Array("10000"))
var iterations: Int = _

def initialSpots(): Vector[Boolean] = {
Vector.tabulate(size) { i => (i % 2) == 0 }
}

private def run(cell: IO[AtomicCell[IO, Vector[Boolean]]]): Unit = {
(cell, Random.scalaUtilRandomSeedLong[IO](seed = 135L))
.flatMapN {
case (data, rnd) =>
data
.evalModify { spots =>
val availableSpots = spots.zipWithIndex.collect { case (true, idx) => idx }
rnd.shuffleVector(availableSpots).map { shuffled =>
val acquired = shuffled.headOption
val next = acquired.fold(spots)(a =>
spots.updated(a, false)) // Mark the chosen spot as taken.
(next, shuffled.headOption)
}
}
.replicateA_(iterations)
}
.unsafeRunSync()
}

@Benchmark
def concurrentEvalModify(): Unit = {
run(cell = AtomicCell.concurrent(initialSpots()))
}

@Benchmark
def asyncEvalModify(): Unit = {
run(cell = AtomicCell.async(initialSpots()))
}
}

0 comments on commit 6c070e1

Please sign in to comment.