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