-
Notifications
You must be signed in to change notification settings - Fork 522
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6160f7b
commit 6c070e1
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
69 changes: 69 additions & 0 deletions
69
benchmarks/src/main/scala/cats/effect/benchmarks/AtomicCellBenchmark.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
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())) | ||
} | ||
} |