Skip to content

Instantly share code, notes, and snippets.

@qwwdfsad
Created March 5, 2019 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qwwdfsad/06c69d6e576541575c17edf6e426ac15 to your computer and use it in GitHub Desktop.
Save qwwdfsad/06c69d6e576541575c17edf6e426ac15 to your computer and use it in GitHub Desktop.
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