1
0
mirror of https://github.com/charlienet/go-mixed.git synced 2025-07-18 08:32:40 +08:00

runtime.nanotime

This commit is contained in:
2022-06-02 15:02:16 +08:00
parent 07273b8b31
commit 1c27b29d27
2 changed files with 29 additions and 8 deletions

View File

@ -2,11 +2,13 @@ package stopwatch
import ( import (
"time" "time"
_ "unsafe"
) )
type watch struct { type watch struct {
startTime time.Time startTime int64
elapsed time.Duration elapsed int64
isRunning bool isRunning bool
} }
@ -19,7 +21,7 @@ func StartNew() *watch {
func (w *watch) Start() { func (w *watch) Start() {
if !w.isRunning { if !w.isRunning {
w.startTime = time.Now() w.startTime = runtimeNano()
w.isRunning = true w.isRunning = true
} }
} }
@ -27,20 +29,21 @@ func (w *watch) Start() {
// 将运行时间重置为零,并开始测量运行时间。 // 将运行时间重置为零,并开始测量运行时间。
func (w *watch) Restart() { func (w *watch) Restart() {
w.elapsed = 0 w.elapsed = 0
w.startTime = time.Now() w.startTime = runtimeNano()
w.isRunning = true w.isRunning = true
} }
// 停止时间间隔测量并将经过的时间重置为零。 // 停止时间间隔测量并将经过的时间重置为零。
func (w *watch) Reset() { func (w *watch) Reset() {
w.elapsed = 0 w.elapsed = 0
w.startTime = time.Now() w.startTime = runtimeNano()
w.isRunning = false w.isRunning = false
} }
func (w *watch) Stop() { func (w *watch) Stop() {
if w.isRunning { if w.isRunning {
num := time.Since(w.startTime) n := runtimeNano()
num := n - w.startTime
w.elapsed += num w.elapsed += num
w.isRunning = false w.isRunning = false
@ -67,10 +70,14 @@ func (w *watch) ElapsedMicroseconds() int64 {
} }
func (w *watch) ElapsedNanoseconds() int64 { func (w *watch) ElapsedNanoseconds() int64 {
now := runtimeNano()
num := w.elapsed num := w.elapsed
if w.isRunning { 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

View File

@ -3,6 +3,7 @@ package stopwatch_test
import ( import (
"testing" "testing"
"time" "time"
_ "unsafe"
"github.com/charlienet/go-mixed/stopwatch" "github.com/charlienet/go-mixed/stopwatch"
) )
@ -28,3 +29,16 @@ func TestWatch(t *testing.T) {
watch.Restart() 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())
}