• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 android.util;
18 
19 import android.annotation.NonNull;
20 import android.os.Build;
21 import android.os.SystemClock;
22 import android.os.Trace;
23 
24 import com.android.internal.annotations.VisibleForTesting;
25 
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.List;
29 
30 /**
31  * Helper class for reporting boot and shutdown timing metrics.
32  *
33  * <p><b>NOTE:</b> This class is not thread-safe. Use a separate copy for other threads.
34  *
35  * @hide
36  */
37 public class TimingsTraceLog {
38     // Debug boot time for every step if it's non-user build.
39     private static final boolean DEBUG_BOOT_TIME = !Build.IS_USER;
40 
41     // Maximum number of nested calls that are stored
42     private static final int MAX_NESTED_CALLS = 10;
43 
44     private final String[] mStartNames;
45     private final long[] mStartTimes;
46 
47     private final String mTag;
48     private final long mTraceTag;
49     private final long mThreadId;
50     private final int mMaxNestedCalls;
51 
52     private int mCurrentLevel = -1;
53 
TimingsTraceLog(String tag, long traceTag)54     public TimingsTraceLog(String tag, long traceTag) {
55         this(tag, traceTag, DEBUG_BOOT_TIME ? MAX_NESTED_CALLS : -1);
56     }
57 
58     @VisibleForTesting
TimingsTraceLog(String tag, long traceTag, int maxNestedCalls)59     public TimingsTraceLog(String tag, long traceTag, int maxNestedCalls) {
60         mTag = tag;
61         mTraceTag = traceTag;
62         mThreadId = Thread.currentThread().getId();
63         mMaxNestedCalls = maxNestedCalls;
64         this.mStartNames = createAndGetStartNamesArray();
65         this.mStartTimes = createAndGetStartTimesArray();
66     }
67 
68     /**
69      * Note: all fields will be copied except for {@code mStartNames} and {@code mStartTimes}
70      * in order to save memory. The copied object is only expected to be used at levels deeper than
71      * the value of {@code mCurrentLevel} when the object is copied.
72      *
73      * @param other object to be copied
74      */
TimingsTraceLog(TimingsTraceLog other)75     protected TimingsTraceLog(TimingsTraceLog other) {
76         this.mTag = other.mTag;
77         this.mTraceTag = other.mTraceTag;
78         this.mThreadId = Thread.currentThread().getId();
79         this.mMaxNestedCalls = other.mMaxNestedCalls;
80         this.mStartNames = createAndGetStartNamesArray();
81         this.mStartTimes = createAndGetStartTimesArray();
82         this.mCurrentLevel = other.mCurrentLevel;
83     }
84 
createAndGetStartNamesArray()85     private String[] createAndGetStartNamesArray() {
86         return mMaxNestedCalls > 0 ? new String[mMaxNestedCalls] : null;
87     }
88 
createAndGetStartTimesArray()89     private long[] createAndGetStartTimesArray() {
90         return mMaxNestedCalls > 0 ? new long[mMaxNestedCalls] : null;
91     }
92 
93     /**
94      * Begin tracing named section
95      * @param name name to appear in trace
96      */
traceBegin(String name)97     public void traceBegin(String name) {
98         assertSameThread();
99         Trace.traceBegin(mTraceTag, name);
100 
101         if (!DEBUG_BOOT_TIME) return;
102 
103         if (mCurrentLevel + 1 >= mMaxNestedCalls) {
104             Slog.w(mTag, "not tracing duration of '" + name + "' because already reached "
105                     + mMaxNestedCalls + " levels");
106             return;
107         }
108 
109         mCurrentLevel++;
110         mStartNames[mCurrentLevel] = name;
111         mStartTimes[mCurrentLevel] = SystemClock.elapsedRealtime();
112     }
113 
114     /**
115      * End tracing previously {@link #traceBegin(String) started} section.
116      *
117      * <p>Also {@link #logDuration logs} the duration.
118      */
traceEnd()119     public void traceEnd() {
120         assertSameThread();
121         Trace.traceEnd(mTraceTag);
122 
123         if (!DEBUG_BOOT_TIME) return;
124 
125         if (mCurrentLevel < 0) {
126             Slog.w(mTag, "traceEnd called more times than traceBegin");
127             return;
128         }
129 
130         final String name = mStartNames[mCurrentLevel];
131         final long duration = SystemClock.elapsedRealtime() - mStartTimes[mCurrentLevel];
132         mCurrentLevel--;
133 
134         logDuration(name, duration);
135     }
136 
assertSameThread()137     private void assertSameThread() {
138         final Thread currentThread = Thread.currentThread();
139         if (currentThread.getId() != mThreadId) {
140             throw new IllegalStateException("Instance of TimingsTraceLog can only be called from "
141                     + "the thread it was created on (tid: " + mThreadId + "), but was from "
142                     + currentThread.getName() + " (tid: " + currentThread.getId() + ")");
143         }
144     }
145 
146     /**
147      * Logs a duration so it can be parsed by external tools for performance reporting.
148      */
logDuration(String name, long timeMs)149     public void logDuration(String name, long timeMs) {
150         Slog.v(mTag, name + " took to complete: " + timeMs + "ms");
151     }
152 
153     /**
154      * Gets the names of the traces that {@link #traceBegin(String) have begun} but
155      * {@link #traceEnd() have not finished} yet.
156      *
157      * <p><b>NOTE:</b> this method is expensive and it should not be used in "production" - it
158      * should only be used for debugging purposes during development (and/or guarded by
159      * static {@code DEBUG} constants that are {@code false}).
160      */
161     @NonNull
getUnfinishedTracesForDebug()162     public final List<String> getUnfinishedTracesForDebug() {
163         if (mStartTimes == null || mCurrentLevel < 0) return Collections.emptyList();
164         final ArrayList<String> list = new ArrayList<>(mCurrentLevel + 1);
165         for (int i = 0; i <= mCurrentLevel; i++) {
166             list.add(mStartNames[i]);
167         }
168         return list;
169     }
170 }
171