Stopwatch

This commit is contained in:
Bixilon 2021-03-22 15:16:28 +01:00
parent 56d942432b
commit 10668e4cc7
No known key found for this signature in database
GPG Key ID: 5CAD791931B09AC4
2 changed files with 55 additions and 3 deletions

View File

@ -0,0 +1,41 @@
/*
* Minosoft
* Copyright (C) 2021 Moritz Zwerger
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program.If not, see <https://www.gnu.org/licenses/>.
*
* This software is not affiliated with Mojang AB, the original developer of Minecraft.
*/
package de.bixilon.minosoft.util
import de.bixilon.minosoft.util.logging.Log
class Stopwatch {
val id = LAST_ID++
private val startTime = System.nanoTime()
private val labs: MutableList<Long> = mutableListOf()
/**
* @return Returns the difference between the last lab and their new one
*/
fun lab(): Long {
val currentTime = System.nanoTime()
val lastLab = labs.getOrNull(0) ?: startTime
labs.add(currentTime)
return currentTime - lastLab
}
fun labPrint() {
val delta = lab()
Log.info("Stop watch ($id) lab: ${UnitFormatter.formatNanos(delta)}")
}
companion object {
private var LAST_ID = 0
}
}

View File

@ -14,8 +14,9 @@
package de.bixilon.minosoft.util
object UnitFormatter {
private val BYTE_UNITS = listOf("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB")
private val UNITS = listOf("", "k", "M", "G", "T", "P", "E", "Z", "Y")
private val BYTE_UNITS = arrayOf("B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB")
private val UNITS = arrayOf("", "k", "M", "G", "T", "P", "E", "Z", "Y")
private val TIME_UNITS = arrayOf("ns", "μs", "ms", "s", "m", "h", "d", "w", "M", "Y")
fun formatBytes(bytes: Long): String {
return formatUnit(bytes, BYTE_UNITS, 1024L)
@ -29,7 +30,7 @@ object UnitFormatter {
return formatUnit(number, UNITS, 1000L)
}
private fun formatUnit(number: Long, units: List<String>, factor: Long): String {
private fun formatUnit(number: Long, units: Array<String>, factor: Long): String {
var lastFactor = 1L
var currentFactor = factor
for (unit in units) {
@ -44,4 +45,14 @@ object UnitFormatter {
}
throw IllegalArgumentException()
}
fun formatNanos(nanos: Long): String {
return "${nanos / 1000000}ms"
// ToDo
}
fun formatMillis(millis: Long): String {
return formatNanos(millis * 1000)
}
}