Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package kotlinx.coroutines.benchmarks
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import org.jetbrains.gradle.benchmarks.*
import kotlin.js.*
import kotlin.random.*
const val batchSize = 15
abstract class BenchmarkBase(private val dispatcher: CoroutineDispatcher) {
private var data = 0.0
@Setup
fun setUp() {
data = Random.nextDouble()
}
@Benchmark
fun asyncAsPromise(): Promise<Double> {
return GlobalScope.async(dispatcher) {
data
}.asPromise()
}
@Benchmark
fun asyncYields(): Promise<Double> {
return GlobalScope.async(dispatcher) {
repeat(batchSize - 1) {
yield()
}
data
}.asPromise()
}
@Benchmark
fun bridgeResolveBenchmark(): Promise<Double> {
val channel = Channel<Unit>(batchSize + 1)
require(channel.offer(Unit))
return GlobalScope.async(dispatcher) {
repeat(batchSize) {
channel.receive()
Promise.resolve(data).then {
require(channel.offer(Unit))
}
}
data
}.asPromise()
}
@Benchmark
fun bridgeSetTimeoutBenchmark(): Promise<Double> {
val channel = Channel<Unit>(batchSize + 1)
require(channel.offer(Unit))
return GlobalScope.async(dispatcher) {
repeat(batchSize) {
channel.receive()
setTimeout({
require(channel.offer(Unit))
}, 0)
}
data
}.asPromise()
}
}
@State(Scope.Benchmark)
class ResolveBenchmark : BenchmarkBase(ResolveDispatcher)
@State(Scope.Benchmark)
class SetTimeoutBenchmark : BenchmarkBase(SetTimeoutDispatcher)
@State(Scope.Benchmark)
class MessageQueueBenchmark : BenchmarkBase(Dispatchers.Default)
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.benchmarks
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.js.*
public object ResolveDispatcher : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
Promise.resolve(Unit).then { block.run() }
}
}
public object SetTimeoutDispatcher : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
setTimeout({
block.run()
}, 0)
}
}
public external fun setTimeout(handler: dynamic, timeout: Int = definedExternally): Int
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment