Skip to content

Commit 1616a7f

Browse files
artyomgopherbot
authored andcommitted
rate: skip time.Now call in Sometimes.Do unless necessary
Don't update Sometimes.last if Interval is not configured. goos: darwin goarch: arm64 pkg: golang.org/x/time/rate │ /tmp/before.txt │ /tmp/after.txt │ │ sec/op │ sec/op vs base │ Sometimes/no-interval-8 14.81n ± 0% 11.96n ± 0% -19.25% (p=0.000 n=10) Sometimes/with-interval-8 27.30n ± 2% 27.57n ± 2% ~ (p=0.780 n=10) geomean 20.10n 18.15n -9.70% goos: linux goarch: arm64 pkg: golang.org/x/time/rate │ /tmp/before-rpi.txt │ /tmp/after-rpi.txt │ │ sec/op │ sec/op vs base │ Sometimes/no-interval-4 89.72n ± 4% 77.03n ± 2% -14.15% (p=0.000 n=10) Sometimes/with-interval-4 147.1n ± 0% 147.8n ± 3% +0.48% (p=0.005 n=10) geomean 114.9n 106.7n -7.12% Change-Id: Ie4a064625432b9628a1cc5686eca9f0b3b90fb7b Reviewed-on: https://go-review.googlesource.com/c/time/+/561956 Reviewed-by: Carlos Amedee <[email protected]> Auto-Submit: Sean Liao <[email protected]> Reviewed-by: Sean Liao <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Michael Knyszek <[email protected]>
1 parent 0c50ed8 commit 1616a7f

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

rate/sometimes.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ func (s *Sometimes) Do(f func()) {
6161
(s.Every > 0 && s.count%s.Every == 0) ||
6262
(s.Interval > 0 && time.Since(s.last) >= s.Interval) {
6363
f()
64-
s.last = time.Now()
64+
if s.Interval > 0 {
65+
s.last = time.Now()
66+
}
6567
}
6668
s.count++
6769
}

rate/sometimes_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,18 @@ func TestSometimesNegative(t *testing.T) {
9292
s.Do(func() {})
9393
s.Do(func() {})
9494
}
95+
96+
func BenchmarkSometimes(b *testing.B) {
97+
b.Run("no-interval", func(b *testing.B) {
98+
s := rate.Sometimes{Every: 10}
99+
for i := 0; i < b.N; i++ {
100+
s.Do(func() {})
101+
}
102+
})
103+
b.Run("with-interval", func(b *testing.B) {
104+
s := rate.Sometimes{Interval: time.Second}
105+
for i := 0; i < b.N; i++ {
106+
s.Do(func() {})
107+
}
108+
})
109+
}

0 commit comments

Comments
 (0)