timer.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2016 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package prometheus
  14. import "time"
  15. // Timer is a helper type to time functions. Use NewTimer to create new
  16. // instances.
  17. type Timer struct {
  18. begin time.Time
  19. observer Observer
  20. }
  21. // NewTimer creates a new Timer. The provided Observer is used to observe a
  22. // duration in seconds. Timer is usually used to time a function call in the
  23. // following way:
  24. //
  25. // func TimeMe() {
  26. // timer := NewTimer(myHistogram)
  27. // defer timer.ObserveDuration()
  28. // // Do actual work.
  29. // }
  30. func NewTimer(o Observer) *Timer {
  31. return &Timer{
  32. begin: time.Now(),
  33. observer: o,
  34. }
  35. }
  36. // ObserveDuration records the duration passed since the Timer was created with
  37. // NewTimer. It calls the Observe method of the Observer provided during
  38. // construction with the duration in seconds as an argument. The observed
  39. // duration is also returned. ObserveDuration is usually called with a defer
  40. // statement.
  41. //
  42. // Note that this method is only guaranteed to never observe negative durations
  43. // if used with Go1.9+.
  44. func (t *Timer) ObserveDuration() time.Duration {
  45. d := time.Since(t.begin)
  46. if t.observer != nil {
  47. t.observer.Observe(d.Seconds())
  48. }
  49. return d
  50. }