github.com/gofiber/fiber/v2@v2.47.0/utils/time_test.go (about) 1 package utils 2 3 import ( 4 "sync/atomic" 5 "testing" 6 "time" 7 ) 8 9 func checkTimeStamp(tb testing.TB, expectedCurrent, actualCurrent uint32) { //nolint:thelper // TODO: Verify if tb can be nil 10 if tb != nil { 11 tb.Helper() 12 } 13 // test with some buffer in front and back of the expectedCurrent time -> because of the timing on the work machine 14 AssertEqual(tb, true, actualCurrent >= expectedCurrent-1 || actualCurrent <= expectedCurrent+1) 15 } 16 17 func Test_TimeStampUpdater(t *testing.T) { 18 t.Parallel() 19 20 StartTimeStampUpdater() 21 22 now := uint32(time.Now().Unix()) 23 checkTimeStamp(t, now, atomic.LoadUint32(&Timestamp)) 24 // one second later 25 time.Sleep(1 * time.Second) 26 checkTimeStamp(t, now+1, atomic.LoadUint32(&Timestamp)) 27 // two seconds later 28 time.Sleep(1 * time.Second) 29 checkTimeStamp(t, now+2, atomic.LoadUint32(&Timestamp)) 30 } 31 32 func Benchmark_CalculateTimestamp(b *testing.B) { 33 StartTimeStampUpdater() 34 35 var res uint32 36 b.Run("fiber", func(b *testing.B) { 37 for n := 0; n < b.N; n++ { 38 res = atomic.LoadUint32(&Timestamp) 39 } 40 checkTimeStamp(b, uint32(time.Now().Unix()), res) 41 }) 42 b.Run("default", func(b *testing.B) { 43 for n := 0; n < b.N; n++ { 44 res = uint32(time.Now().Unix()) 45 } 46 checkTimeStamp(b, uint32(time.Now().Unix()), res) 47 }) 48 }