1package metrics 2 3import ( 4 "sync/atomic" 5 "time" 6) 7 8// The timer type is used to store a duration. 9type Timer struct { 10 val int64 11 desc *desc 12} 13 14// Name returns the name of the timer. 15func (t *Timer) Name() string { return t.desc.Name } 16 17// Value atomically returns the value of the timer. 18func (t *Timer) Value() time.Duration { return time.Duration(atomic.LoadInt64(&t.val)) } 19 20// Update sets the timer value to d. 21func (t *Timer) Update(d time.Duration) { atomic.StoreInt64(&t.val, int64(d)) } 22 23// UpdateSince sets the timer value to the difference between since and the current time. 24func (t *Timer) UpdateSince(since time.Time) { t.Update(time.Since(since)) } 25 26// String returns a string representation using the name and value of the timer. 27func (t *Timer) String() string { return t.desc.Name + ": " + time.Duration(t.val).String() } 28 29// Time updates the timer to the duration it takes to call f. 30func (t *Timer) Time(f func()) { 31 s := time.Now() 32 f() 33 t.UpdateSince(s) 34} 35