1 /*
2  * Copyright (C) 2018 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.google.android.setupcompat.logging;
18 
19 import android.util.Log;
20 import com.google.android.setupcompat.internal.ClockProvider;
21 import com.google.android.setupcompat.internal.Preconditions;
22 
23 /** Convenience utility to log duration events. Please note that this class is not thread-safe. */
24 public final class Timer {
25   /** Creates a new instance of timer for the given {@code metricKey}. */
Timer(MetricKey metricKey)26   public Timer(MetricKey metricKey) {
27     this.metricKey = metricKey;
28   }
29 
30   /**
31    * Starts the timer and notes the current clock time.
32    *
33    * @throws IllegalStateException if the timer was stopped.
34    */
start()35   public void start() {
36     Preconditions.checkState(!isStopped(), "Timer cannot be started once stopped.");
37     if (isStarted()) {
38       Log.wtf(
39           TAG,
40           String.format(
41               "Timer instance was already started for: %s at [%s].", metricKey, startInNanos));
42       return;
43     }
44     startInNanos = ClockProvider.timeInNanos();
45   }
46 
47   /**
48    * Stops the watch and the current clock time is noted.
49    *
50    * @throws IllegalStateException if the watch was not started.
51    */
stop()52   public void stop() {
53     Preconditions.checkState(isStarted(), "Timer must be started before it can be stopped.");
54     if (isStopped()) {
55       Log.wtf(
56           TAG,
57           String.format(
58               "Timer instance was already stopped for: %s at [%s]", metricKey, stopInNanos));
59       return;
60     }
61     stopInNanos = ClockProvider.timeInNanos();
62   }
63 
isStopped()64   boolean isStopped() {
65     return stopInNanos != 0;
66   }
67 
isStarted()68   private boolean isStarted() {
69     return startInNanos != 0;
70   }
71 
getDurationInNanos()72   long getDurationInNanos() {
73     return stopInNanos - startInNanos;
74   }
75 
getMetricKey()76   MetricKey getMetricKey() {
77     return metricKey;
78   }
79 
80   private long startInNanos;
81   private long stopInNanos;
82   private final MetricKey metricKey;
83 
84   private static final String TAG = "SetupCompat.Timer";
85 }
86