Created
June 30, 2023 12:21
-
-
Save iblinov65apps/c65f9628bc572cf7038059095e0b5384 to your computer and use it in GitHub Desktop.
composition time logger
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 net.ppldo.comment.android.messages.content | |
interface CompositionTimeLogger { | |
fun start() | |
fun logNext(name: String) | |
fun logAll() | |
} | |
class DummyCompositionTimeLogger : CompositionTimeLogger { | |
override fun start() { | |
// no op | |
} | |
override fun logNext(name: String) { | |
// no op | |
} | |
override fun logAll() { | |
// no op | |
} | |
} |
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 net.ppldo.comment.android.messages.content | |
class CompositionTimeLoggerImpl( | |
private val tag: String, | |
private val maxNameLength: Int = MAX_NAME_LENGTH, | |
) : CompositionTimeLogger { | |
private var lastTime = current() | |
private val map = mutableMapOf<String, Long>() | |
override fun start() { | |
lastTime = current() | |
} | |
override fun logNext(name: String) { | |
val currentTime = current() | |
val millis = currentTime - lastTime | |
map[name] = map.getOrDefault(name, 0) + millis | |
println("$tag: ${formatName(name)}: $millis ms " + visualizeMillis(millis)) | |
lastTime = current() | |
} | |
override fun logAll() { | |
val log = buildString { | |
append(tag) | |
append(" result: ") | |
map.forEach { (t, u) -> | |
append(t) | |
append(':') | |
append(u) | |
append(", ") | |
} | |
} | |
println(log) | |
} | |
private fun current() = System.currentTimeMillis() | |
private fun formatName(name: String) = | |
if (name.length < MAX_NAME_LENGTH) { | |
buildString { | |
repeat(maxNameLength - name.length) { | |
append(' ') | |
} | |
append(name) | |
} | |
} else { | |
name.substring(name.length - maxNameLength) | |
} | |
private fun visualizeMillis(millis: Long): String { | |
if (millis == 0L) return "" | |
return buildString { | |
repeat(millis.toInt()) { | |
append('*') | |
} | |
} | |
} | |
} | |
private const val MAX_NAME_LENGTH = 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment