1 /* 2 * Copyright (C) 2012 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.contacts.common.util; 18 19 import android.util.Log; 20 import java.util.ArrayList; 21 22 /** A {@link StopWatch} records start, laps and stop, and print them to logcat. */ 23 public class StopWatch { 24 25 private final String mLabel; 26 27 private final ArrayList<Long> mTimes = new ArrayList<>(); 28 private final ArrayList<String> mLapLabels = new ArrayList<>(); 29 StopWatch(String label)30 private StopWatch(String label) { 31 mLabel = label; 32 lap(""); 33 } 34 35 /** Create a new instance and start it. */ start(String label)36 public static StopWatch start(String label) { 37 return new StopWatch(label); 38 } 39 40 /** Return a dummy instance that does no operations. */ getNullStopWatch()41 public static StopWatch getNullStopWatch() { 42 return NullStopWatch.INSTANCE; 43 } 44 45 /** Record a lap. */ lap(String lapLabel)46 public void lap(String lapLabel) { 47 mTimes.add(System.currentTimeMillis()); 48 mLapLabels.add(lapLabel); 49 } 50 51 /** Stop it and log the result, if the total time >= {@code timeThresholdToLog}. */ stopAndLog(String TAG, int timeThresholdToLog)52 public void stopAndLog(String TAG, int timeThresholdToLog) { 53 54 lap(""); 55 56 final long start = mTimes.get(0); 57 final long stop = mTimes.get(mTimes.size() - 1); 58 59 final long total = stop - start; 60 if (total < timeThresholdToLog) { 61 return; 62 } 63 64 final StringBuilder sb = new StringBuilder(); 65 sb.append(mLabel); 66 sb.append(","); 67 sb.append(total); 68 sb.append(": "); 69 70 long last = start; 71 for (int i = 1; i < mTimes.size(); i++) { 72 final long current = mTimes.get(i); 73 sb.append(mLapLabels.get(i)); 74 sb.append(","); 75 sb.append((current - last)); 76 sb.append(" "); 77 last = current; 78 } 79 Log.v(TAG, sb.toString()); 80 } 81 82 private static class NullStopWatch extends StopWatch { 83 84 public static final NullStopWatch INSTANCE = new NullStopWatch(); 85 NullStopWatch()86 public NullStopWatch() { 87 super(null); 88 } 89 90 @Override lap(String lapLabel)91 public void lap(String lapLabel) { 92 // noop 93 } 94 95 @Override stopAndLog(String TAG, int timeThresholdToLog)96 public void stopAndLog(String TAG, int timeThresholdToLog) { 97 // noop 98 } 99 } 100 } 101