blob: 9c7f38a6f9f05e4558082581d50c5d06a652441d (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package benchmarks
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.openjdk.jmh.annotations.*
import java.util.concurrent.*
import kotlin.coroutines.*
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(1)
open class ChannelSinkBenchmark {
private val tl = ThreadLocal.withInitial({ 42 })
private val tl2 = ThreadLocal.withInitial({ 239 })
private val unconfined = Dispatchers.Unconfined
private val unconfinedOneElement = Dispatchers.Unconfined + tl.asContextElement()
private val unconfinedTwoElements = Dispatchers.Unconfined + tl.asContextElement() + tl2.asContextElement()
@Benchmark
fun channelPipeline(): Int = runBlocking {
run(unconfined)
}
@Benchmark
fun channelPipelineOneThreadLocal(): Int = runBlocking {
run(unconfinedOneElement)
}
@Benchmark
fun channelPipelineTwoThreadLocals(): Int = runBlocking {
run(unconfinedTwoElements)
}
private suspend inline fun run(context: CoroutineContext): Int {
return Channel
.range(1, 1_000_000, context)
.filter(context) { it % 4 == 0 }
.fold(0) { a, b -> a + b }
}
private fun Channel.Factory.range(start: Int, count: Int, context: CoroutineContext) = GlobalScope.produce(context) {
for (i in start until (start + count))
send(i)
}
}
|