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 17package android.net.util; 18 19import android.os.SystemClock; 20 21 22/** 23 * @hide 24 */ 25public class Stopwatch { 26 private long mStartTimeMs; 27 private long mStopTimeMs; 28 29 public boolean isStarted() { 30 return (mStartTimeMs > 0); 31 } 32 33 public boolean isStopped() { 34 return (mStopTimeMs > 0); 35 } 36 37 public boolean isRunning() { 38 return (isStarted() && !isStopped()); 39 } 40 41 // Returning |this| makes possible the following usage pattern: 42 // 43 // Stopwatch s = new Stopwatch().start(); 44 public Stopwatch start() { 45 if (!isStarted()) { 46 mStartTimeMs = SystemClock.elapsedRealtime(); 47 } 48 return this; 49 } 50 51 // Returns the total time recorded, in milliseconds, or 0 if not started. 52 public long stop() { 53 if (isRunning()) { 54 mStopTimeMs = SystemClock.elapsedRealtime(); 55 } 56 // Return either the delta after having stopped, or 0. 57 return (mStopTimeMs - mStartTimeMs); 58 } 59 60 // Returns the total time recorded to date, in milliseconds. 61 // If the Stopwatch is not running, returns the same value as stop(), 62 // i.e. either the total time recorded before stopping or 0. 63 public long lap() { 64 if (isRunning()) { 65 return (SystemClock.elapsedRealtime() - mStartTimeMs); 66 } else { 67 return stop(); 68 } 69 } 70 71 public void reset() { 72 mStartTimeMs = 0; 73 mStopTimeMs = 0; 74 } 75} 76