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 com.android.dialer.common.LogUtil; 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 /** Record a lap. */ lap(String lapLabel)41 public void lap(String lapLabel) { 42 mTimes.add(System.currentTimeMillis()); 43 mLapLabels.add(lapLabel); 44 } 45 46 /** Stop it and log the result, if the total time >= {@code timeThresholdToLog}. */ stopAndLog(String TAG, int timeThresholdToLog)47 public void stopAndLog(String TAG, int timeThresholdToLog) { 48 49 lap(""); 50 51 final long start = mTimes.get(0); 52 final long stop = mTimes.get(mTimes.size() - 1); 53 54 final long total = stop - start; 55 if (total < timeThresholdToLog) { 56 return; 57 } 58 59 final StringBuilder sb = new StringBuilder(); 60 sb.append(mLabel); 61 sb.append(","); 62 sb.append(total); 63 sb.append(": "); 64 65 long last = start; 66 for (int i = 1; i < mTimes.size(); i++) { 67 final long current = mTimes.get(i); 68 sb.append(mLapLabels.get(i)); 69 sb.append(","); 70 sb.append((current - last)); 71 sb.append(" "); 72 last = current; 73 } 74 LogUtil.v(TAG, sb.toString()); 75 } 76 } 77