github.com/klaytn/klaytn@v1.12.1/common/profile/profile.go (about) 1 // Copyright 2018 The klaytn Authors 2 // This file is part of the klaytn library. 3 // 4 // The klaytn library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The klaytn library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the klaytn library. If not, see <http://www.gnu.org/licenses/>. 16 17 package profile 18 19 import ( 20 "fmt" 21 "sync" 22 "time" 23 ) 24 25 type TimeRecord struct { 26 count int 27 duration time.Duration 28 } 29 30 type Profiler struct { 31 profMap map[string]*TimeRecord 32 33 // TODO: Use simple synchronization mechanism for thread safety. 34 // TODO: Need improvement 35 mutex sync.Mutex 36 } 37 38 func (p *Profiler) Profile(key string, d time.Duration) { 39 p.mutex.Lock() 40 41 if r, ok := p.profMap[key]; ok { 42 r.count += 1 43 r.duration += d 44 } else { 45 p.profMap[key] = &TimeRecord{count: 1, duration: d} 46 } 47 48 p.mutex.Unlock() 49 } 50 51 func (p *Profiler) PrintProfileInfo() { 52 fmt.Printf("%s", p.GetProfileInfoString()) 53 } 54 55 func (p *Profiler) GetProfileInfoString() string { 56 str := fmt.Sprintf("Key,Count,Time\n") 57 for k, v := range p.profMap { 58 str += fmt.Sprintf("%s,%d,%f\n", k, v.count, v.duration.Seconds()) 59 } 60 61 return str 62 } 63 64 func NewProfiler() *Profiler { 65 return &Profiler{ 66 profMap: make(map[string]*TimeRecord), 67 } 68 } 69 70 var Prof = NewProfiler()