Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare concurrency of various SegmentPool strategies
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
You can’t perform that action at this time.