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.net.util; 18 19 import android.os.SystemClock; 20 21 22 /** 23 * @hide 24 */ 25 public class Stopwatch { 26 private long mStartTimeNs; 27 private long mStopTimeNs; 28 isStarted()29 public boolean isStarted() { 30 return (mStartTimeNs > 0); 31 } 32 isStopped()33 public boolean isStopped() { 34 return (mStopTimeNs > 0); 35 } 36 isRunning()37 public boolean isRunning() { 38 return (isStarted() && !isStopped()); 39 } 40 41 /** 42 * Start the Stopwatch. 43 */ start()44 public Stopwatch start() { 45 if (!isStarted()) { 46 mStartTimeNs = SystemClock.elapsedRealtimeNanos(); 47 } 48 return this; 49 } 50 51 /** 52 * Restart the Stopwatch. 53 */ restart()54 public Stopwatch restart() { 55 mStartTimeNs = SystemClock.elapsedRealtimeNanos(); 56 mStopTimeNs = 0; 57 return this; 58 } 59 60 /** 61 * Stop the Stopwatch. 62 * @return the total time recorded, in microseconds, or 0 if not started. 63 */ stop()64 public long stop() { 65 if (isRunning()) { 66 mStopTimeNs = SystemClock.elapsedRealtimeNanos(); 67 } 68 // Return either the delta after having stopped, or 0. 69 return (mStopTimeNs - mStartTimeNs) / 1000; 70 } 71 72 /** 73 * Return the total time recorded to date, in microseconds. 74 * If the Stopwatch is not running, returns the same value as stop(), 75 * i.e. either the total time recorded before stopping or 0. 76 */ lap()77 public long lap() { 78 if (isRunning()) { 79 return (SystemClock.elapsedRealtimeNanos() - mStartTimeNs) / 1000; 80 } else { 81 return stop(); 82 } 83 } 84 85 /** 86 * Reset the Stopwatch. It will be stopped when this method returns. 87 */ reset()88 public void reset() { 89 mStartTimeNs = 0; 90 mStopTimeNs = 0; 91 } 92 } 93