bitbucket.org/ai69/amoy@v0.2.3/stopwatch.go (about) 1 package amoy 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "time" 8 9 "github.com/1set/gut/yos" 10 ) 11 12 // Stopwatch provides a set of methods to measure elapsed time. 13 type Stopwatch struct { 14 start time.Time 15 } 16 17 // NewStopwatch returns a Stopwatch instance which just starts to measure. 18 func NewStopwatch() *Stopwatch { 19 return &Stopwatch{start: time.Now()} 20 } 21 22 // Elapsed returns the total elapsed time measured by the current instance. 23 func (sw *Stopwatch) Elapsed() time.Duration { 24 return time.Since(sw.start) 25 } 26 27 // ElapsedMilliseconds returns the total elapsed time measured by the current instance, in milliseconds. 28 func (sw *Stopwatch) ElapsedMilliseconds() int64 { 29 return time.Since(sw.start).Milliseconds() 30 } 31 32 // Show outputs elapsed time measured by the current instance to console. 33 func (sw *Stopwatch) Show() { 34 var ( 35 elapsed = sw.Elapsed() 36 title = "⏱️ Time Cost" 37 ) 38 if !yos.IsOnWindows() { 39 title = StyleDate(title) 40 } 41 f := bufio.NewWriter(os.Stdout) 42 defer f.Flush() 43 fmt.Fprintf(f, "%s: %v\n", title, elapsed) 44 }