我需要检查一个函数需要运行多长时间.我有以下功能来解决相同的任务: mixAnimalsA fun mixAnimalsA(a1: Animal, a2: Animal) = when (setOf(a1, a2)) { setOf(Animal.OWL, Animal.Leopard) - Beast.OWLPARD setOf(Animal.EL
mixAnimalsA
fun mixAnimalsA(a1: Animal, a2: Animal) = when (setOf(a1, a2)) { setOf(Animal.OWL, Animal.Leopard) -> Beast.OWLPARD setOf(Animal.ELEPHANT, Animal.BUTTERFLY) -> Beast.BUTTERPHANT else -> throw Exception("Not possible combination") }
mixAnimalsB
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") }
动物和野兽是枚举.如何衡量每个函数运行的时间?
如果您正在寻找代码内解决方案,可以使用measureTimeMillis
和
measureNanoTime
,如下所示:
val time = measureTimeMillis { // call your function here }
它们分别以毫秒和纳秒返回测量的时间.