github.com/sandwich-go/boost@v1.3.29/xtest/quantile.go (about) 1 package xtest 2 3 import ( 4 "fmt" 5 "sort" 6 "sync" 7 "time" 8 ) 9 10 var durationsMap = make(map[string][]time.Duration) 11 var durationsMapMutex sync.RWMutex 12 13 // AddDuration 添加key所用的耗时 14 func AddDuration(key string, duration time.Duration) { 15 durationsMapMutex.Lock() 16 defer durationsMapMutex.Unlock() 17 durations := durationsMap[key] 18 durations = append(durations, duration) 19 durationsMap[key] = durations 20 } 21 22 // PrintPercentiles 打印耗时数据 23 func PrintPercentiles(percentiles ...float32) { 24 durationsMapMutex.Lock() 25 defer durationsMapMutex.Unlock() 26 results := CalculatePercentiles(durationsMap, percentiles) 27 fmt.Printf("=== xtest package cost percentiles result(%d) === \n", len(durationsMap)) 28 for key := range durationsMap { 29 fmt.Printf("Key: %s\n", key) 30 for i, percentile := range percentiles { 31 fmt.Printf(" Percentile %.2f: %.2f seconds\n", percentile, results[key][i].Seconds()) 32 } 33 fmt.Println() 34 } 35 } 36 37 // CalculatePercentiles 计算耗时数据 38 func CalculatePercentiles(durationsMap map[string][]time.Duration, percentiles []float32) map[string][]time.Duration { 39 results := make(map[string][]time.Duration) 40 for key, durations := range durationsMap { 41 // Sort the durations in ascending order 42 sortedDurations := make([]time.Duration, len(durations)) 43 copy(sortedDurations, durations) 44 sort.Slice(sortedDurations, func(i, j int) bool { 45 return sortedDurations[i] < sortedDurations[j] 46 }) 47 // Calculate percentiles 48 percentileDurations := make([]time.Duration, len(percentiles)) 49 for i, p := range percentiles { 50 index := int(float32(len(sortedDurations)-1) * p) 51 percentileDurations[i] = sortedDurations[index] 52 } 53 results[key] = percentileDurations 54 } 55 return results 56 }