1 /** 2 * Copyright (C) 2020 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.android.providers.media.tests.utils; 18 19 import android.os.Bundle; 20 import android.os.SystemClock; 21 22 import android.util.Log; 23 24 import androidx.test.InstrumentationRegistry; 25 26 import java.util.concurrent.TimeUnit; 27 28 /** 29 * General Timer function for MediaProvider tests. 30 */ 31 public class Timer { 32 private static final String TAG = "Timer"; 33 34 private final String name; 35 private int count; 36 private long duration; 37 private long start; 38 private long maxRunDuration = 0; 39 Timer(String name)40 public Timer(String name) { 41 this.name = name; 42 } 43 start()44 public void start() { 45 if (start != 0) { 46 throw new IllegalStateException(); 47 } else { 48 start = SystemClock.elapsedRealtimeNanos(); 49 } 50 } 51 stop()52 public void stop() { 53 long currentRunDuration = 0; 54 if (start == 0) { 55 throw new IllegalStateException(); 56 } else { 57 currentRunDuration = (SystemClock.elapsedRealtimeNanos() - start); 58 maxRunDuration = (currentRunDuration > maxRunDuration) ? currentRunDuration : 59 maxRunDuration; 60 duration += currentRunDuration; 61 start = 0; 62 count++; 63 } 64 } 65 getAverageDurationMillis()66 public long getAverageDurationMillis() { 67 return TimeUnit.MILLISECONDS.convert(duration / count, TimeUnit.NANOSECONDS); 68 } 69 getMaxDurationMillis()70 public long getMaxDurationMillis() { 71 return TimeUnit.MILLISECONDS.convert(maxRunDuration, TimeUnit.NANOSECONDS); 72 } 73 dumpResults()74 public void dumpResults() { 75 final long duration = getAverageDurationMillis(); 76 Log.v(TAG, name + ": " + duration + "ms"); 77 78 final Bundle results = new Bundle(); 79 results.putLong(name, duration); 80 InstrumentationRegistry.getInstrumentation().sendStatus(0, results); 81 } 82 } 83