1 /**
2  * Copyright (C) 2023 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.rkpdapp.utils;
18 
19 import android.os.SystemClock;
20 import android.util.Log;
21 
22 /**
23  * Restartable stopwatch class that can be used to measure multiple start->stop time
24  * intervals. All measured time intervals are summed and returned by getElapsedMillis.
25  */
26 public class StopWatch implements AutoCloseable {
27     private final String mTag;
28     private long mStartTime = 0;
29     private long mElapsedTime = 0;
30 
StopWatch(String tag)31     public StopWatch(String tag) {
32         mTag = tag;
33     }
34 
35     /** Start or resume a timer. */
start()36     public void start() {
37         if (isRunning()) {
38             Log.w(mTag, "Starting a timer that's already been running for "
39                     + getElapsedMillis() + "ms");
40         } else {
41             mStartTime = SystemClock.elapsedRealtime();
42         }
43     }
44 
45     /** Stop recording time. */
stop()46     public void stop() {
47         if (!isRunning()) {
48             Log.w(mTag, "Attempting to stop a timer that hasn't been started.");
49         } else {
50             mElapsedTime += SystemClock.elapsedRealtime() - mStartTime;
51             mStartTime = 0;
52         }
53     }
54 
55     /** Stops the timer if it's running. */
56     @Override
close()57     public void close() {
58         if (isRunning()) {
59             stop();
60         }
61     }
62 
63     /** Get how long the timer has been recording. */
getElapsedMillis()64     public int getElapsedMillis() {
65         if (isRunning()) {
66             return (int) (mElapsedTime + SystemClock.elapsedRealtime() - mStartTime);
67         } else {
68             return (int) mElapsedTime;
69         }
70     }
71 
72     /** Is the timer currently recording time? */
isRunning()73     public boolean isRunning() {
74         return mStartTime != 0;
75     }
76 }
77 
78