Created
June 13, 2020 15:34
-
-
Save swankjesse/95bf5687ad40b6dc47386d348079a623 to your computer and use it in GitHub Desktop.
Compare concurrency of various SegmentPool strategies
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
package okio.samples | |
import okio.Buffer | |
import okio.BufferedSink | |
import okio.BufferedSource | |
import okio.buffer | |
import okio.source | |
import java.io.File | |
import java.util.concurrent.atomic.AtomicLong | |
class ConcurrencyBenchmark( | |
private val file: File | |
) { | |
private val cycleCount = AtomicLong() | |
private fun loop() { | |
var a = Buffer() | |
file.source().buffer().use { source -> | |
a.writeAll(source) | |
} | |
var b = Buffer() | |
while (true) { | |
processLines(a, b) | |
val c = a | |
a = b | |
b = c | |
cycleCount.incrementAndGet() | |
} | |
} | |
private fun processLines(source: BufferedSource, sink: BufferedSink) { | |
while (true) { | |
val line = source.readUtf8Line() ?: break | |
sink.writeUtf8(line) | |
sink.writeUtf8("\n") | |
} | |
} | |
fun printStats() { | |
var lastSuccessCount = cycleCount.get() | |
var lastTime = System.nanoTime() | |
while (true) { | |
val currentSuccessCount = cycleCount.get() | |
val currentTime = System.nanoTime() | |
val elapsedSeconds = (currentTime - lastTime) / 1_000_000_000.0 | |
val successPerSecond = (currentSuccessCount - lastSuccessCount) / elapsedSeconds | |
println(String.format("%10.2f success/sec", successPerSecond)) | |
lastSuccessCount = currentSuccessCount | |
lastTime = currentTime | |
Thread.sleep(250) | |
} | |
} | |
fun runThreads(threadCount: Int) { | |
for (t in 0 until threadCount) { | |
val thread = object : Thread("benchmark-thread-$t") { | |
override fun run() { | |
loop() | |
} | |
} | |
thread.start() | |
} | |
} | |
} | |
fun main() { | |
val concurrencyBenchmark = ConcurrencyBenchmark( | |
file = File("/Users/jwilson/Projects/okio/settings.gradle") | |
) | |
concurrencyBenchmark.runThreads(128) | |
concurrencyBenchmark.printStats() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment