github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/lib/hrtime/time_windows_test.go (about)

     1  //go:build windows
     2  // +build windows
     3  
     4  package hrtime
     5  
     6  import (
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  func TestHighResolutionTime(t *testing.T) {
    14  	t.Run("use default windows tr around 15.6ms", func(tt *testing.T) {
    15  		ClockInit()
    16  		_ = ResetTimeResolutionFrom1ms()
    17  		t1 := time.Now()
    18  		tt.Logf("system clock current time: %v\n", t1)
    19  		time.Sleep(200 * time.Millisecond)
    20  		t2, t3, t4 := NowInDefaultTZ(), NowIn(TzUtc8Offset), time.Now()
    21  		tt.Logf("windows non-sys clock current time in default tz: %v; in asia tz: %v\n", t2, t3)
    22  		tt.Logf("system clock current time: %v\n", t4)
    23  		elapsedMs := MonotonicElapsed().Milliseconds()
    24  		tt.Logf("elapsed ms: %d\n", elapsedMs)
    25  		assert.True(tt, t2.UnixMilli()-t1.UnixMilli()-1 <= elapsedMs && t2.UnixMilli()-t1.UnixMilli()+1 >= elapsedMs)
    26  		assert.True(tt, t4.UnixMilli()-t1.UnixMilli()-1 <= elapsedMs && t4.UnixMilli()-t1.UnixMilli()+1 >= elapsedMs)
    27  		time.Sleep(500 * time.Millisecond)
    28  		elapsedMs = int64(750)
    29  		e1, e2 := time.Since(t1).Milliseconds(), MonotonicElapsed().Milliseconds()
    30  		tt.Logf("e1: %v; e2: %v\n", e1, e2)
    31  		assert.GreaterOrEqual(tt, elapsedMs, e1)
    32  		assert.GreaterOrEqual(tt, elapsedMs, e2)
    33  	})
    34  	t.Run("set windows tr to 1ms by ClockInit", func(tt *testing.T) {
    35  		ClockInit()
    36  		defer func() {
    37  			_ = ResetTimeResolutionFrom1ms()
    38  		}()
    39  		t1 := time.Now()
    40  		tt.Logf("system clock current time: %v\n", t1)
    41  		time.Sleep(200 * time.Millisecond)
    42  		t2, t3, t4 := NowInDefaultTZ(), NowIn(TzUtc8Offset), time.Now()
    43  		tt.Logf("windows non-sys clock current time in default tz: %v; in asia tz: %v\n", t2, t3)
    44  		tt.Logf("system clock current time: %v\n", t4)
    45  		elapsedMs := MonotonicElapsed().Milliseconds()
    46  		tt.Logf("elapsed ms: %d\n", elapsedMs)
    47  		assert.True(tt, t2.UnixMilli()-t1.UnixMilli()-1 <= elapsedMs && t2.UnixMilli()-t1.UnixMilli()+1 >= elapsedMs)
    48  		assert.True(tt, t4.UnixMilli()-t1.UnixMilli()-1 <= elapsedMs && t4.UnixMilli()-t1.UnixMilli()+1 >= elapsedMs)
    49  		time.Sleep(500 * time.Millisecond)
    50  		windowsElapsedMs, defaultElapsed := time.Since(t1).Milliseconds(), MonotonicElapsed().Milliseconds()
    51  		assert.GreaterOrEqual(tt, windowsElapsedMs, defaultElapsed)
    52  	})
    53  }