You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: iteration.md
+15-5Lines changed: 15 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -97,19 +97,19 @@ Writing [benchmarks](https://golang.org/pkg/testing/#hdr-Benchmarks) in Go is an
97
97
98
98
```go
99
99
funcBenchmarkRepeat(b *testing.B) {
100
-
fori:=0; i < b.N; i++ {
100
+
forb.Loop() {
101
101
Repeat("a")
102
102
}
103
103
}
104
104
```
105
105
106
106
You'll see the code is very similar to a test.
107
107
108
-
The `testing.B` gives you access to the cryptically named `b.N`.
108
+
The `testing.B` gives you access to the loop function. `Loop()` returns true as long as the benchmark should continue running.
109
109
110
-
When the benchmark code is executed, it runs `b.N`times and measures how long it takes.
110
+
When the benchmark code is executed, it measures how long it takes. After `Loop()` returns false, `b.N`contains the total number of iterations that ran.
111
111
112
-
The amount of times the code is run shouldn't matter to you, the framework will determine what is a "good" value for that to let you have some decent results.
112
+
The number of times the code is run shouldn't matter to you, the framework will determine what is a "good" value for that to let you have some decent results.
113
113
114
114
To run the benchmarks do `go test -bench=.` (or if you're in Windows Powershell `go test -bench="."`)
115
115
@@ -125,7 +125,17 @@ What `136 ns/op` means is our function takes on average 136 nanoseconds to run \
125
125
126
126
**Note:** By default benchmarks are run sequentially.
127
127
128
-
**Note:** Sometimes, Go can optimize your benchmarks in a way that makes them inaccurate, such as eliminating the function being benchmarked. Check your benchmarks to see if the values make sense. If they seem overly optimized, you can follow the strategies in this **[blog post](https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go)**.
128
+
Only the body of the loop is timed; it automatically excludes setup and cleanup code from benchmark timing. A typical benchmark is structured like:
129
+
130
+
```go
131
+
funcBenchmark(b *testing.B) {
132
+
//... setup ...
133
+
for b.Loop() {
134
+
//... code to measure ...
135
+
}
136
+
//... cleanup ...
137
+
}
138
+
```
129
139
130
140
Strings in Go are immutable, meaning every concatenation, such as in our `Repeat` function, involves copying memory to accommodate the new string. This impacts performance, particularly during heavy string concatenation.
0 commit comments