• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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.messaging.util;
18 
19 import android.os.SystemClock;
20 
21 /**
22  * A utility timer that logs the execution time of operations
23  */
24 public class LoggingTimer {
25     private static final int NO_WARN_LIMIT = -1;
26 
27     private final String mTag;
28     private final String mName;
29     private final long mWarnLimitMillis;
30     private long mStartMillis;
31 
LoggingTimer(final String tag, final String name)32     public LoggingTimer(final String tag, final String name) {
33         this(tag, name, NO_WARN_LIMIT);
34     }
35 
LoggingTimer(final String tag, final String name, final long warnLimitMillis)36     public LoggingTimer(final String tag, final String name, final long warnLimitMillis) {
37         mTag = tag;
38         mName = name;
39         mWarnLimitMillis = warnLimitMillis;
40     }
41 
42     /**
43      * This method should be called at the start of the operation to be timed.
44      */
start()45     public void start() {
46         mStartMillis = SystemClock.elapsedRealtime();
47 
48         if (LogUtil.isLoggable(mTag, LogUtil.VERBOSE)) {
49             LogUtil.v(mTag, "Timer start for " + mName);
50         }
51     }
52 
53     /**
54      * This method should be called at the end of the operation to be timed. It logs the time since
55      * the last call to {@link #start}
56      */
stopAndLog()57     public void stopAndLog() {
58         final long elapsedMs = SystemClock.elapsedRealtime() - mStartMillis;
59 
60         final String logMessage = String.format("Used %dms for %s", elapsedMs, mName);
61 
62         LogUtil.save(LogUtil.DEBUG, mTag, logMessage);
63 
64         if (mWarnLimitMillis != NO_WARN_LIMIT && elapsedMs > mWarnLimitMillis) {
65             LogUtil.w(mTag, logMessage);
66         } else if (LogUtil.isLoggable(mTag, LogUtil.VERBOSE)) {
67             LogUtil.v(mTag, logMessage);
68         }
69     }
70 }
71