-
-
Save ablx/586d701a839b821253244c5d81cb36e4 to your computer and use it in GitHub Desktop.
full
This file contains hidden or 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
import java.util.LinkedList | |
import java.util.concurrent.TimeUnit | |
import kotlin.system.measureNanoTime | |
import kotlin.system.measureTimeMillis | |
import kotlin.time.ExperimentalTime | |
import kotlin.time.measureTime | |
import kotlin.time.measureTimedValue | |
fun main(args: Array<String>) { | |
javaStyle() | |
kotlin1() | |
kotlin2() | |
kotlin3() | |
} | |
@OptIn(ExperimentalTime::class) | |
fun kotlin3() { | |
val arrayListValue = measureTimedValue { | |
arrayListCode() | |
} | |
println("ArrayList ook ${arrayListValue.duration.inWholeSeconds} seconds and got ${arrayListValue.value}.") | |
val (value,duration) = measureTimedValue { linkedListCode() } | |
println("LinkedList took ${duration.inWholeSeconds} seconds and got ${value}.") | |
} | |
@OptIn(ExperimentalTime::class) | |
fun kotlin2() { | |
val arrayListDuration = measureTime { | |
arrayListCode() | |
} | |
println("ArrayList took ${arrayListDuration.inWholeSeconds} seconds and got ?") | |
val linkedListDuration = measureTime { | |
linkedListCode() | |
} | |
println("LinkedList took ${linkedListDuration.inWholeSeconds} seconds and got ?") | |
} | |
fun kotlin1() { | |
val arrayListDuration = measureNanoTime { | |
arrayListCode() | |
} | |
println("ArrayList took ${TimeUnit.NANOSECONDS.toSeconds(arrayListDuration)} seconds and got ?") | |
val linkedListDuration = measureTimeMillis { | |
linkedListCode() | |
} | |
println("LinkedList took ${TimeUnit.NANOSECONDS.toSeconds(linkedListDuration)} seconds and got ?") | |
} | |
fun javaStyle() { | |
val begin = System.nanoTime() | |
val result = arrayListCode() | |
val duration = System.nanoTime() - begin | |
println("ArrayList took ${TimeUnit.NANOSECONDS.toSeconds(duration)} seconds and got $result.") | |
val begin2 = System.nanoTime() | |
val result2 = linkedListCode() | |
println("LinkedList took ${TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - begin2)} seconds and got $result2.") | |
} | |
private fun linkedListCode() = fillList(LinkedList()) | |
private fun arrayListCode() = fillList(ArrayList()) | |
fun fillList(list: MutableList<Int>): Int { | |
(0..50_000000).forEach { list.add(it) } | |
return list.reduce { acc, i -> acc + i } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment