Safemotion Lib
Loading...
Searching...
No Matches
timer.py
Go to the documentation of this file.
1# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
2# -*- coding: utf-8 -*-
3
4from time import perf_counter
5from typing import Optional
6
7
8class Timer:
9 """
10 A timer which computes the time elapsed since the start/reset of the timer.
11 """
12
13 def __init__(self):
14 self.reset()
15
16 def reset(self):
17 """
18 Reset the timer.
19 """
20 self._start = perf_counter()
21 self._paused: Optional[float] = None
23 self._count_start = 1
24
25 def pause(self):
26 """
27 Pause the timer.
28 """
29 if self._paused is not None:
30 raise ValueError("Trying to pause a Timer that is already paused!")
31 self._paused = perf_counter()
32
33 def is_paused(self) -> bool:
34 """
35 Returns:
36 bool: whether the timer is currently paused
37 """
38 return self._paused is not None
39
40 def resume(self):
41 """
42 Resume the timer.
43 """
44 if self._paused is None:
45 raise ValueError("Trying to resume a Timer that is not paused!")
46 self._total_paused += perf_counter() - self._paused
47 self._paused = None
48 self._count_start += 1
49
50 def seconds(self) -> float:
51 """
52 Returns:
53 (float): the total number of seconds since the start/reset of the
54 timer, excluding the time when the timer is paused.
55 """
56 if self._paused is not None:
57 end_time: float = self._paused # type: ignore
58 else:
59 end_time = perf_counter()
60 return end_time - self._start - self._total_paused
61
62 def avg_seconds(self) -> float:
63 """
64 Returns:
65 (float): the average number of seconds between every start/reset and
66 pause.
67 """
68 return self.seconds() / self._count_start
float avg_seconds(self)
Definition timer.py:62
float seconds(self)
Definition timer.py:50