1 /*
<lambda>null2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.example.testapp
18 
19 class TimingTracker(
20     private val numberOfIterations: Int = 1,
21     private var numberOfIterationsToIgnore: Int = 0
22 ) {
23     init {
24         require(numberOfIterations > numberOfIterationsToIgnore)
25     }
26     private val timings = mutableMapOf<String, IntArray>()
27     private var currentIteration: Int = 0
28     fun nextIteration() {
29         currentIteration++
30     }
31     fun <T> measure(name: String, workToTime: () -> T): T {
32         val start = System.nanoTime()
33         val t = workToTime()
34         if (currentIteration >= numberOfIterationsToIgnore) {
35             val end = System.nanoTime()
36             val deltaInMicroseconds: Int = ((end - start) / 1000).toInt()
37             val timing = timings.getOrPut(name) {
38                 IntArray(numberOfIterations - numberOfIterationsToIgnore)
39             }
40             timing[currentIteration - numberOfIterationsToIgnore] += deltaInMicroseconds
41         }
42         return t
43     }
44     fun report(): String {
45         var minimum: Int = Int.MAX_VALUE
46         for (timing in timings.values) {
47             val m = timing.minOrNull()
48             if (m != null && m < minimum) minimum = m
49         }
50 
51         println(timings.map { (name, timing) -> name + ": " + timing.minOrNull() }.joinToString(separator = "\n"))
52 
53         return (timings.map { (name, timing) -> name + ": " + timing.joinToString() }.joinToString() + "\n\n" +
54                 timings.map { (name, timing) -> name + ": " + timing.joinToString { "%.2f".format(it.toFloat() / minimum) } }.joinToString() + "\n\n" +
55                 timings.map { (name, timing) -> name + ": " + timing.minOrNull() }.joinToString())
56     }
57 }
58 
59