Skip to content

Instantly share code, notes, and snippets.

@octylFractal
Created August 24, 2020 19:22
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 octylFractal/c7f3862bd568c6f69a81bf5e6d62d1c9 to your computer and use it in GitHub Desktop.
Save octylFractal/c7f3862bd568c6f69a81bf5e6d62d1c9 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.*
import java.nio.ByteBuffer
import java.util.*
import kotlin.system.measureTimeMillis
suspend fun main() {
withContext(Dispatchers.Default) {
val timeAlloc = measureTimeMillis {
System.err.println(hashBuffers { ByteBuffer.allocate(it) })
}
System.err.println("Time to normal allocate: ${timeAlloc}ms")
val timeAllocDirect = measureTimeMillis {
System.err.println(hashBuffers { ByteBuffer.allocateDirect(it) })
}
System.err.println("Time to direct allocate: ${timeAllocDirect}ms")
val timeAllocDirectOnIO = measureTimeMillis {
System.err.println(hashBuffers { withContext(Dispatchers.IO) { ByteBuffer.allocateDirect(it) } })
}
System.err.println("Time to direct allocate on IO: ${timeAllocDirectOnIO}ms")
}
}
suspend inline fun hashBuffers(crossinline allocate: suspend (size: Int) -> ByteBuffer): Int {
return coroutineScope {
(1..100_000)
.map {
async {
allocate(8192)
}
}
.awaitAll()
.fold(0, { hash, buffer -> Objects.hash(hash, System.identityHashCode(buffer)) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment