diff --git a/stopwatch/stopwatch.go b/stopwatch/stopwatch.go index b49681b..a493a6b 100644 --- a/stopwatch/stopwatch.go +++ b/stopwatch/stopwatch.go @@ -2,11 +2,13 @@ package stopwatch import ( "time" + + _ "unsafe" ) type watch struct { - startTime time.Time - elapsed time.Duration + startTime int64 + elapsed int64 isRunning bool } @@ -19,7 +21,7 @@ func StartNew() *watch { func (w *watch) Start() { if !w.isRunning { - w.startTime = time.Now() + w.startTime = runtimeNano() w.isRunning = true } } @@ -27,20 +29,21 @@ func (w *watch) Start() { // 将运行时间重置为零,并开始测量运行时间。 func (w *watch) Restart() { w.elapsed = 0 - w.startTime = time.Now() + w.startTime = runtimeNano() w.isRunning = true } // 停止时间间隔测量并将经过的时间重置为零。 func (w *watch) Reset() { w.elapsed = 0 - w.startTime = time.Now() + w.startTime = runtimeNano() w.isRunning = false } func (w *watch) Stop() { if w.isRunning { - num := time.Since(w.startTime) + n := runtimeNano() + num := n - w.startTime w.elapsed += num w.isRunning = false @@ -67,10 +70,14 @@ func (w *watch) ElapsedMicroseconds() int64 { } func (w *watch) ElapsedNanoseconds() int64 { + now := runtimeNano() num := w.elapsed if w.isRunning { - num += time.Since(w.startTime) + num += now - w.startTime } - return num.Nanoseconds() + return num } + +//go:linkname runtimeNano runtime.nanotime +func runtimeNano() int64 diff --git a/stopwatch/stopwatch_test.go b/stopwatch/stopwatch_test.go index e267915..6ada7d6 100644 --- a/stopwatch/stopwatch_test.go +++ b/stopwatch/stopwatch_test.go @@ -3,6 +3,7 @@ package stopwatch_test import ( "testing" "time" + _ "unsafe" "github.com/charlienet/go-mixed/stopwatch" ) @@ -28,3 +29,16 @@ func TestWatch(t *testing.T) { watch.Restart() } + +func TestStop(t *testing.T) { + watch := stopwatch.StartNew() + time.Sleep(time.Second) + + watch.Stop() + time.Sleep(time.Second) + watch.Start() + + time.Sleep(time.Second) + + t.Log(watch.Elapsed()) +}