| # |
| # Copyright (C) 2016 The Android Open Source Project |
| # |
| # Licensed under the Apache License, Version 2.0 (the "License"); |
| # you may not use this file except in compliance with the License. |
| # You may obtain a copy of the License at |
| # |
| # http://www.apache.org/licenses/LICENSE-2.0 |
| # |
| # Unless required by applicable law or agreed to in writing, software |
| # distributed under the License is distributed on an "AS IS" BASIS, |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| # See the License for the specific language governing permissions and |
| # limitations under the License. |
| # |
| |
| """A general-purpose timer.""" |
| |
| |
| import time |
| |
| |
| class Timer(object): |
| """A simple object to time various things. |
| |
| Attributes: |
| name: The name of what is being timed. |
| label: (optional) An additional text label for the timing. Default None. |
| """ |
| |
| _all_timers = [] |
| _group_paused_timers = [] |
| |
| @classmethod |
| def MassPauseRunningTimers(cls): |
| """Pauses all running timers.""" |
| timers_to_pause = [t for t in cls._all_timers if t.IsRunning()] |
| for t in timers_to_pause: |
| t.Stop() |
| cls._group_paused_timers += timers_to_pause |
| |
| @classmethod |
| def ResumeMassPausedTimers(cls): |
| """Resumes all timers that were paused using |
| cls.MassPauseRunningTimers() |
| """ |
| for t in cls._group_paused_timers: |
| t.Start() |
| cls._group_paused_timers = [] |
| |
| def __init__(self, name, label=None): |
| self._all_timers.append(self) |
| self.name = name |
| self.label = label |
| self._start_time = None |
| self.Reset() |
| |
| def Reset(self): |
| """Resets the timer, stopping it and setting it to 0.""" |
| self._time = 0 |
| self._start_time = None |
| |
| def Start(self): |
| """Starts the timer continuing from whatever time is showing. |
| |
| Does nothing to a timer that is already running. |
| """ |
| if self._start_time is None: |
| self._start_time = time.time() |
| |
| def Stop(self): |
| """Stops the timer, leaving its current amount of time showing.""" |
| if self._start_time is not None: |
| self._time += time.time() - self._start_time |
| self._start_time = None |
| |
| def IsRunning(self): |
| return self._start_time is not None |
| |
| def Read(self): |
| """Read the current time of the timer in seconds with float precision. |
| |
| Works while running, but best practice would be to Stop first. |
| """ |
| # Amount of time previously timed. |
| result = self._time |
| # If currently running, look at the time elapsed since last stop. |
| if self._start_time is not None: |
| result += time.time() - self._start_time |
| |
| return result |