如何才能获得测试Kotlin中函数性能所需的时间

时间:2017-05-21 16:56:42

标签: performance kotlin

我需要检查一个函数需要运行多长时间。我有以下功能来处理相同的任务:

mixAnimalsA

fun mixAnimalsB(a1: Animal, a2: Animal) =
        when (setOf(a1, a2)) {
            (c1 == Animal.OWL && c2 == Animal.Leopard) ||
                    (c2 == Animal.OWL && c1 == Animal.Leopard) -> Beast.OWLPARD
            (c1 == Animal.ELEPHANT && c2 == Animal.BUTTERFLY) ||
                    (c2 == Animal.ELEPHANT && c1 == Animal.BUTTERFLY)-> Beast.BUTTERPHANT
            else -> throw Exception("Not possible combination")
        }

mixAnimalsB

Animal

BeastULocale ulocale = com.ibm.icu.util.ULocale .forLocale(Locale.forLanguageTag(language)); UnicodeSet set = LocaleData.getExemplarSet(ulocale, LocaleData.ES_STANDARD); Iterator<String> iterator = set.iterator(); StringBuffer buf = new StringBuffer(); while (iterator.hasNext()) { buf.append(iterator.next()); } return buf.toString(); 是枚举。如何衡量每个函数运行的时间?

5 个答案:

答案 0 :(得分:11)

如果您正在寻找代码内解决方案,可以使用measureTimeMillismeasureNanoTime,如下所示:

val time = measureTimeMillis {
    // call your function here
}

它们分别以毫秒和纳秒为单位返回测量时间。

答案 1 :(得分:6)

被测块返回结果

我想测量一种方法的时间,我也需要随后的结果。因此,我创建了以下功能:

inline fun <R> executeAndMeasureTimeMillis(block: () -> R): Pair<R, Long> {
    val start = System.currentTimeMillis()
    val result = block()
    return result to (System.currentTimeMillis() - start)
}

您可以这样称呼它:

val (response, duration) = executeAndMeasureTimeMillis {
    restTemplate.getForObject<AnyObject>(uri)
}

答案 2 :(得分:2)

如果足以将时间作为控制台上的输出:

fun <T> timeIt(message: String = "", block: () -> T): T {
    val start = System.currentTimeMillis()
    val r = block()
    val end = System.currentTimeMillis()
    println("$message: ${end - start} ms")
    return r
}

用法:

val result = timeIt("note about the code") {
   // do something...
}

输出(示例):

  

注意代码:1ms

答案 3 :(得分:0)

对于某些代码块的基准测试并同时获得结果,我对TimingKt类中的标准方法进行了一些重构 给我们输出一般结果,并同时显示给定的日志。 这是我的示例:

/**
     * Executes the given block and show the elapsed time in milliseconds in a given message.
     *
     * @param block which will be bench marked
     * @param logMessage log message to be displayed
     *
     * @return a generic result
     *
     */
    private fun <T> measureTime(block: () -> T, logMessage: String): T {
        val start = System.currentTimeMillis()
        val t = block()
        val consumedTime = System.currentTimeMillis() - start
        Log.d(TAG, "Calculation of $logMessage time :$consumedTime milliseconds")
        return t
    }

以及如何使用它:

return measureTime({ 
// given block with return result
}, "message to be displayed typically the name of method which will be calculated") 

答案 4 :(得分:0)

这是我简单的时间测试代码。

class TimeCounter(val name: String) {
    var totalTime: Long = 0
        private set

    var count: Int = 0
        private set

    var minTime: Long = Long.MAX_VALUE
        private set

    var maxTime: Long = Long.MIN_VALUE
        private set

    fun addTime(time: Long) {
        this.count++
        this.totalTime += time

        if (this.minTime > time) {
            this.minTime = time
        }

        if (this.maxTime < time) {
            this.maxTime = time
        }
    }

    val averageTime: Double
        get() = this.totalTime / this.count.toDouble()

    fun printTime() {
        println("(time about : '$name'), totalTime : $totalTime, count : $count, " +
                "average : $averageTime, minTime : $minTime, maxTime : $maxTime")
    }

    fun <T> runWithTimeCount(run: () -> T): T {
        val startTime = System.currentTimeMillis()
        return run().also {
            this.addTime(System.currentTimeMillis() - startTime)
        }
    }
}

您可以像这样使用“ TimeCounter”(示例)

var sum = 0
val testTimeCounter = TimeCounter("logic1")
for(i in 0 until 100){
    sum += testTimeCounter.runWithTimeCount { 
        logic1(i) // your logic
    }
}

println(sum)
testTimeCounter.printTime()