From 1c864333cac25273ebfcefa53d50a82c270ebdab Mon Sep 17 00:00:00 2001 From: Ian Lance Taylor Date: Thu, 21 Mar 2024 11:33:24 -0700 Subject: [PATCH] runtime: add fast path for (*timers).adjust MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affected benchmark results, including new benchmark (some of these may just be noise, of course): AdjustTimers10000-12 797.7µ ± 2% 709.6µ ± 2% -11.04% (p=0.000 n=10) TickerResetNaive-12 62.69n ± 1% 63.56n ± 1% +1.40% (p=0.018 n=10) NowUnixMicro-12 29.95n ± 1% 30.25n ± 4% +1.00% (p=0.024 n=10) ParseDuration-12 81.88n ± 0% 81.45n ± 0% -0.51% (p=0.006 n=10) UnmarshalText-12 186.9n ± 1% 185.2n ± 1% -0.88% (p=0.006 n=10) geomean 151.8n 151.2n -0.40% Change-Id: I3ef8356249c5d703b314498e34ee8095093671c8 Reviewed-on: https://go-review.googlesource.com/c/go/+/573455 Reviewed-by: Austin Clements LUCI-TryBot-Result: Go LUCI Auto-Submit: Ian Lance Taylor Reviewed-by: Ian Lance Taylor Commit-Queue: Ian Lance Taylor --- src/runtime/time.go | 5 +++++ src/time/sleep_test.go | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/runtime/time.go b/src/runtime/time.go index 31c83ca4e3..06a56bf7ae 100644 --- a/src/runtime/time.go +++ b/src/runtime/time.go @@ -778,6 +778,11 @@ func (ts *timers) adjust(now int64, force bool) { throw("bad ts") } + if t.astate.Load()&(timerModified|timerZombie) == 0 { + // Does not need adjustment. + continue + } + t.lock() if t.state&timerHeaped == 0 { badTimer() diff --git a/src/time/sleep_test.go b/src/time/sleep_test.go index 634a5c7a13..29f56ef752 100644 --- a/src/time/sleep_test.go +++ b/src/time/sleep_test.go @@ -971,3 +971,21 @@ func doWork(dur Duration) { for Since(start) < dur { } } + +func BenchmarkAdjustTimers10000(b *testing.B) { + benchmark(b, func(pb *testing.PB) { + for pb.Next() { + const n = 10000 + timers := make([]*Timer, 0, n) + for range n { + t := AfterFunc(Hour, func() {}) + timers = append(timers, t) + } + timers[n-1].Reset(Nanosecond) + Sleep(Microsecond) + for _, t := range timers { + t.Stop() + } + } + }) +}