Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created April 5, 2019 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save montanaflynn/a3a2c303f20bc1ca45fd505686a55c49 to your computer and use it in GitHub Desktop.
Save montanaflynn/a3a2c303f20bc1ca45fd505686a55c49 to your computer and use it in GitHub Desktop.
A simple timer to use for logging time between actions
package timer
import (
"log"
"os"
"time"
)
type TimeLogger interface {
Printf(format string, v ...interface{})
}
type Timer struct {
start time.Time
logger TimeLogger
message string
active bool
}
func (t *Timer) Start() {
if t.active {
t.start = time.Now()
}
}
func (t *Timer) Stop() *Timer {
if t.active {
t.logger.Printf("%s in %.03f seconds", t.message, time.Since(t.start).Seconds())
}
return t
}
func (t *Timer) Restart(message string) {
if t.active {
t.start = time.Now()
t.message = message
}
}
func (t *Timer) StopAndRestart(message string) {
if t.active {
t.Stop()
t.start = time.Now()
t.message = message
}
}
func NewTimer(message string, active bool, logger ...TimeLogger) Timer {
if !active {
return Timer{active: active}
}
if logger[0] == nil {
logger[0] = log.New(os.Stdout, "Timer: ", log.LstdFlags)
}
return Timer{start: time.Now(), message: message, logger: logger[0], active: active}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment