测试顺序会影响性能结果吗?

时间:2019-06-17 06:24:29

标签: java kotlin junit

我写了2块时间测量代码。 t1 的打印结果总是比 t2 大。
Block1和block2完全相同。如果我在块1之前写了块2,则 t2 的打印结果比 t1 小得多。 我不知道为什么会这样。

@Test
fun test(){
    val list = (1..100000).toList()

    //block 1
    var t1 = System.nanoTime()
    list.filter { it % 7 == 0 }
    t1 = System.nanoTime() - t1

    //block 2
    var t2 = System.nanoTime()
    list.filter { it % 7 == 0  }
    t2 = System.nanoTime() - t2

    //print
    println(t1)
    println(t2)
}

1 个答案:

答案 0 :(得分:5)

您遇到的事情称为预热。对Kotlin(以及其他基于JVm的语言)的首次请求通常比平均响应时间要慢得多。这个预热期是由延迟类加载和及时编译引起的。

有几种方法可以更可靠地衡量性能。其中之一是在执行测试本身之前手动创建预热。更加可靠的方法是使用专门的库,例如JMH

手动预热示例:

// warmup
for (i in 1..9999) {
    val list = (1..100000).toList()
    list.filter { it % 7 == 0 }
}

// rest of the test

作为附带说明,Kotlin具有内置功能,您可以使用它们来代替手动计算时差。有measureTimeMillismeasureNanoTime

它会这样使用:

val time = measureNanoTime {
    list.filter { it % 7 == 0 }
}
相关问题