diff --git a/stopwatch.go b/stopwatch.go index 52b6b09..7dc8396 100644 --- a/stopwatch.go +++ b/stopwatch.go @@ -94,8 +94,8 @@ func (s *Stopwatch) Start() { } } -// Elapsed time is the time the stopwatch has been active -func (s *Stopwatch) elapsedTime() time.Duration { +// ElapsedTime is the time the stopwatch has been active +func (s *Stopwatch) ElapsedTime() time.Duration { if s.active() { return time.Since(s.start) } @@ -106,18 +106,13 @@ func (s *Stopwatch) elapsedTime() time.Duration { func (s *Stopwatch) LapTime() time.Duration { s.RLock() defer s.RUnlock() - return s.elapsedTime() - s.mark + return s.ElapsedTime() - s.mark } // Lap starts a new lap, and returns the length of // the previous one. func (s *Stopwatch) Lap(state string) Lap { - s.Lock() - defer s.Unlock() - lap := Lap{formatter: s.formatter, state: state, duration: s.elapsedTime() - s.mark} - s.mark = s.elapsedTime() - s.laps = append(s.laps, lap) - return lap + return s.LapWithData(state, nil) } // LapWithData starts a new lap, and returns the length of @@ -126,8 +121,9 @@ func (s *Stopwatch) Lap(state string) Lap { func (s *Stopwatch) LapWithData(state string, data map[string]interface{}) Lap { s.Lock() defer s.Unlock() - lap := Lap{formatter: s.formatter, state: state, duration: s.elapsedTime() - s.mark, data: data} - s.mark = s.elapsedTime() + elapsed := s.ElapsedTime() + lap := Lap{formatter: s.formatter, state: state, duration: elapsed - s.mark, data: data} + s.mark = elapsed s.laps = append(s.laps, lap) return lap } diff --git a/stopwatch_test.go b/stopwatch_test.go index 801af53..53474cb 100644 --- a/stopwatch_test.go +++ b/stopwatch_test.go @@ -165,3 +165,42 @@ func TestInactiveStart(t *testing.T) { t.Errorf("After Reset(), Laps() should be empty") } } + +func TestTimeTotal(t *testing.T) { + t.Parallel() + + sw := New(0, false) + totalAfterStart := sw.ElapsedTime().Nanoseconds() + if totalAfterStart != 0 { + t.Errorf("TotalTime must be zero after stopwatch creation") + } + sw.Start() + sw.Lap("first") + totalAfterLap1 := sw.ElapsedTime().Nanoseconds() + if totalAfterLap1 <= 0 { + t.Errorf("TotalTime must be grater than zero after lap 1") + } + sw.Lap("second") + totalAfterLap2 := sw.ElapsedTime().Nanoseconds() + if totalAfterLap2 <= totalAfterLap1 { + t.Errorf("TotalTime after lap 2 must be greater then after lap 1") + } + sw.Stop() + totalAfterStop1 := sw.ElapsedTime().Nanoseconds() + totalAfterStop2 := sw.ElapsedTime().Nanoseconds() + if totalAfterStop1 != totalAfterStop2 { + t.Errorf("TotalTime must not change after stop") + } + + sw.Start() + + totalAfterRestart1 := sw.ElapsedTime().Nanoseconds() + totalAfterRestart2 := sw.ElapsedTime().Nanoseconds() + if totalAfterRestart1 >= totalAfterRestart2 { + t.Errorf("TotalTime must run after restart") + } + if totalAfterRestart1 <= totalAfterStop2 { + t.Errorf("TotalTime after restart must only grow") + } + +}