trpc.group/trpc-go/trpc-go@v1.0.3/metrics/timer.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 package metrics 15 16 import ( 17 "time" 18 ) 19 20 // ITimer is the interface that emits timer metrics. 21 type ITimer interface { 22 23 // Record records the duration since timer.start, and reset timer.start. 24 Record() time.Duration 25 26 // RecordDuration records duration into timer, and reset timer.start. 27 RecordDuration(duration time.Duration) 28 29 // Reset resets the timer.start. 30 Reset() 31 } 32 33 // timer defines the timer metric. timer is reported to each external Sink-able system. 34 type timer struct { 35 name string 36 start time.Time 37 } 38 39 // Record records the time cost since last Record. 40 func (t *timer) Record() time.Duration { 41 duration := time.Since(t.start) 42 if len(metricsSinks) == 0 { 43 return duration 44 } 45 t.start = time.Now() 46 r := NewSingleDimensionMetrics(t.name, float64(duration), PolicyTimer) 47 for _, sink := range metricsSinks { 48 sink.Report(r) 49 } 50 return duration 51 } 52 53 // RecordDuration records duration and reset t.start to now. 54 func (t *timer) RecordDuration(duration time.Duration) { 55 if len(metricsSinks) == 0 { 56 return 57 } 58 t.start = time.Now() 59 r := NewSingleDimensionMetrics(t.name, float64(duration), PolicyTimer) 60 for _, sink := range metricsSinks { 61 sink.Report(r) 62 } 63 } 64 65 // Reset resets the start time of timer to now. 66 func (t *timer) Reset() { 67 t.start = time.Now() 68 }