1
0

stopwatch.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2024 The Ebitengine Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package audio
  15. import (
  16. "sync"
  17. "time"
  18. )
  19. type stopwatch struct {
  20. duration time.Duration
  21. lastStarted time.Time
  22. running bool
  23. m sync.Mutex
  24. }
  25. func (s *stopwatch) start() {
  26. s.m.Lock()
  27. defer s.m.Unlock()
  28. if s.running {
  29. return
  30. }
  31. s.lastStarted = time.Now()
  32. s.running = true
  33. }
  34. func (s *stopwatch) stop() {
  35. s.m.Lock()
  36. defer s.m.Unlock()
  37. if !s.running {
  38. return
  39. }
  40. s.duration += time.Since(s.lastStarted)
  41. s.running = false
  42. }
  43. func (s *stopwatch) current() time.Duration {
  44. s.m.Lock()
  45. defer s.m.Unlock()
  46. d := s.duration
  47. if s.running {
  48. d += time.Since(s.lastStarted)
  49. }
  50. return d
  51. }
  52. func (s *stopwatch) reset() {
  53. s.m.Lock()
  54. defer s.m.Unlock()
  55. s.duration = 0
  56. s.lastStarted = time.Time{}
  57. s.running = false
  58. }