1/*
2 * Copyright (C) 2013 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 */
16package com.android.mail.perf;
17
18import android.os.SystemClock;
19import android.text.TextUtils;
20
21import com.android.mail.utils.LogUtils;
22
23/**
24 * A simple perf timer class that supports lap-time-style measurements. Once a
25 * timer is started, any number of laps can be marked, but they are all relative
26 * to the original start time.
27 */
28public class SimpleTimer {
29
30    private static final String DEFAULT_LOG_TAG = "SimpleTimer";
31
32    private static final boolean ENABLE_SIMPLE_TIMER = false;
33
34    private final boolean mEnabled;
35    private long mStartTime;
36    private long mLastMarkTime;
37    private String mSessionName;
38
39    public SimpleTimer() {
40        this(false);
41    }
42
43    public SimpleTimer(boolean enabled) {
44        mEnabled = enabled;
45    }
46
47    public final boolean isEnabled() {
48        return ENABLE_SIMPLE_TIMER && LogUtils.isLoggable(getTag(), LogUtils.DEBUG)
49                && mEnabled;
50    }
51
52    public SimpleTimer withSessionName(String sessionName) {
53        mSessionName = sessionName;
54        return this;
55    }
56
57    public void start() {
58        mStartTime = mLastMarkTime = SystemClock.uptimeMillis();
59        LogUtils.d(getTag(), "timer START");
60    }
61
62    public void mark(String msg) {
63        if (isEnabled()) {
64            long now = SystemClock.uptimeMillis();
65            LogUtils.d(getTag(), "[%s] %sms elapsed (%sms since last mark)", msg, now - mStartTime,
66                    now - mLastMarkTime);
67            mLastMarkTime = now;
68        }
69    }
70
71    private String getTag() {
72        return TextUtils.isEmpty(mSessionName) ? DEFAULT_LOG_TAG : mSessionName;
73    }
74
75}
76