Created
April 5, 2019 11:21
-
-
Save montanaflynn/a3a2c303f20bc1ca45fd505686a55c49 to your computer and use it in GitHub Desktop.
A simple timer to use for logging time between actions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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