CodeGym /课程 /Go SELF /Go 中的基准测试:BenchmarkXxx、b.ResetTimer、-bench、-benchtime

Go 中的基准测试:BenchmarkXxx、b.ResetTimer、-bench、-benchtime

Go SELF
第 71 级, 课程 3
可用

1. Why benchmarks are needed

If you have ever optimized code “by eye”, then you are already familiar with the fantasy genre. In your head it seems that strings.Builder is definitely faster than concatenation; that one sort is “fine, probably”; that memory allocations are “not that scary”. And then it turns out that you optimized not the bottleneck, but merely made the code less readable.

A benchmark is a small test that runs the needed piece of code many times and measures how much one operation costs on average. Important: a benchmark does not prove that code is “good”. It helps compare two approaches under the same load and stop arguing “in the chat” about who is right.

Where the benchmark lives: BenchmarkXxx(b *testing.B)

By structure, a benchmark is very similar to an ordinary test: it lives in a *_test.go file and is run with the go test command. It is not some separate “profiler from space”, but part of the standard Go testing toolkit.

By analogy with how go test finds and runs Example... functions in *_test.go, a similar rule applies to benchmarks: the function must start with Benchmark and accept *testing.B.

The skeleton looks like this:


package taskapp

import "testing"

func BenchmarkSomething(b *testing.B) {
    // measured code goes here
}

The name after Benchmark is the benchmark name. That is the name you will later use to choose what to run via -bench.

2. Iterations: b.N and b.Loop()

b.N and why we do not write “1000 times”

When a beginner sees a benchmark, they often expect something like: “run 1 000 000 times and measure.” But Go is smarter: it chooses the number of iterations itself so that the measurement is long enough and stable. For this, *testing.B has the b.N field: the number of iterations the runner selected for this run.

All you have to do is honestly perform the measured operation b.N times:

package taskapp

import "testing"

func BenchmarkAdd(b *testing.B) {
    x := 0
    for i := 0; i < b.N; i++ {
        x += i
    }
    _ = x
}

Why is this better than a “fixed number”? Because for fast operations, 1000 iterations are too few (the time will be noisy), and for slow ones, too many (you will wait forever). The runner balances this automatically.

for b.Loop() {}

In modern Go, improvements have appeared that make benchmarks less error-prone. For example, starting with Go 1.24, benchmarks can use testing.B.Loop() instead of a manual loop over b.N. This is designed as a faster and less fragile way to organize iterations.

If you see code like this, do not panic:

package taskapp

import "testing"

func BenchmarkNormalizeTitleLoop(b *testing.B) {
    raw := "  BUY MILK  "
    b.ResetTimer()

    for b.Loop() {
        _ = NormalizeTitle(raw)
    }
}

In meaning, it is the same thing: perform the measured action the required number of times, as determined by the runner. The syntax is just more “direct” and usually reduces the chance of making a mistake with loop boundaries.

Within this lecture, we still continue to confidently use the classic for i := 0; i < b.N; i++, because it appears in a huge amount of code and it is important to be able to read it.

4. Timer: b.ResetTimer, b.StopTimer, b.StartTimer

b.ResetTimer(): how not to measure data preparation instead of the algorithm

One of the most common mistakes is accidentally measuring not what you intended. For example, you want to measure string search speed, but in reality you are measuring test data generation, file reading, building a huge array, or some other “preparatory” work.

For this, benchmarks have an important ritual: first do the setup, then say “okay, measure from here on” with b.ResetTimer().

Imagine that in our educational app (a hypothetical taskapp) we have task title normalization: trim spaces from the ends and convert to a uniform form. Let us make a simple function:

package taskapp

import "strings"

func NormalizeTitle(s string) string {
    s = strings.TrimSpace(s)
    return strings.ToLower(s)
}

Now a benchmark with test string preparation:

package taskapp

import (
    "strings"
    "testing"
)

var sinkString string // sink for the result (explained below)

func BenchmarkNormalizeTitle(b *testing.B) {
    // setup: prepare the input
    raw := strings.Repeat("  BUY MILK  ", 100)

    b.ResetTimer() // only NormalizeTitle is measured from here on
    for i := 0; i < b.N; i++ {
        sinkString = NormalizeTitle(raw)
    }
}

The idea of b.ResetTimer() is simple: everything before it is considered setup and should not affect the final numbers.

When ResetTimer is not enough: StopTimer() and StartTimer()

Sometimes data preparation is needed not only “once before the loop”, but, for example, inside each iteration (and you want to exclude this preparation from the measurements). In such cases, use b.StopTimer() and b.StartTimer().

The basic principle is the same: you should measure the part about which you are drawing conclusions. If you need to “turn off the stopwatch” while preparing, you can do that.

If you start juggling StopTimer/StartTimer frequently, that is a signal that you are measuring a scenario that is too complex for a microbenchmark.

5. Running and parameters: -bench, -run, -benchtime

-bench as a filter

By default, Benchmark... functions do not necessarily run during a normal go test. Usually, you run them explicitly: you tell the test runner which benchmarks to run via the -bench flag.

Command example (for reference):

go test -bench=.

Here . means “all benchmarks”. You can also choose a specific benchmark or a group by name, because -bench accepts a pattern (a regular expression in the style of go test).

To avoid also running all unit tests in parallel (which is sometimes just slow), people often add -run with a deliberately nonexistent test:

go test -run TestDoesNotExist -bench=BenchmarkNormalizeTitle

The idea is: “do not run tests, but do run the benchmark.” This is useful when you have many tests and are currently focusing only on measurements.

-benchtime: when the numbers “jump around”

Sometimes you run a benchmark and see that the results fluctuate: 50 ns/op one time, 70 ns/op the next. This is partly normal: the system does not have to be perfectly stable (background load, scheduler, cache warmup, CPU frequencies).

The -benchtime flag lets you tell the runner: “let us measure longer” (or, conversely, shorter). The longer the measurement, the smaller the relative noise. Therefore, when comparing two variants that are close in speed, it is useful to increase the duration.

Example (for reference):

go test -run TestDoesNotExist -bench=BenchmarkNormalizeTitle -benchtime=2s

It is important to understand the philosophy: -benchtime is not a “computer speed booster”. It is a request for the runner to collect statistics for longer so that the conclusion is more reliable.

How to read benchmark output

When you run a benchmark, Go prints lines roughly like this:

BenchmarkNormalizeTitle-8    3000000    420 ns/op

It is useful to read this line as: “on my machine (and with this number of threads/CPU) one operation costs N nanoseconds on average.” The iteration count (3000000) is not your goal, but simply what the runner decided to execute in order to collect statistics.

If you are comparing two approaches, do not draw conclusions from a single run. Run it several times and see whether one variant is consistently better than the other. And if the difference is within the noise, perhaps you are trying to optimize something that is not a problem in the first place.

6. Sink variable: how not to measure the compiler’s optimization

Here the classic story happens: you wrote a benchmark, and the compiler looked at it and said, “Hmm, the result is not used anywhere. That means we can throw the computation away as garbage.” And you happily measure almost nothing.

To prevent this, the result of the computation must be made “observable”: store it in a variable that lives long enough and that the compiler cannot simply ignore. The simplest option is a package-level variable:

package taskapp

import "testing"

var sinkInt int

func BenchmarkSum(b *testing.B) {
    s := 0
    for i := 0; i < b.N; i++ {
        s += i
    }
    sinkInt = s
}

Yes, it looks like a “magic global.” But this is precisely a technical trick for measurements. We would not do this in ordinary business code, but in benchmarks it is a normal practice.

7. Mini-scenario: benchmarking output string formatting

In apps like a “task manager”, there is often code that forms a string for output: one task → one line in a table/log. This is not necessarily the bottleneck, but it is a convenient example because it is easy to understand and measure.

Let us make two versions: a naïve one using + and a more careful one using strings.Builder. We are not teaching a new package here; we are simply measuring the effect.

package taskapp

import "strconv"

type Task struct {
    ID    int
    Title string
    Done  bool
}

func FormatTaskPlus(t Task) string {
    return "#" + strconv.Itoa(t.ID) + " " + t.Title
}

And the Builder version:

package taskapp

import (
    "strconv"
    "strings"
)

func FormatTaskBuilder(t Task) string {
    var b strings.Builder
    b.WriteByte('#')
    b.WriteString(strconv.Itoa(t.ID))
    b.WriteByte(' ')
    b.WriteString(t.Title)
    return b.String()
}

Now the benchmarks, where we honestly separate data preparation:

package taskapp

import "testing"

var sinkFmt string

func BenchmarkFormatTaskPlus(b *testing.B) {
    t := Task{ID: 42, Title: "buy milk", Done: false}

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        sinkFmt = FormatTaskPlus(t)
    }
}

func BenchmarkFormatTaskBuilder(b *testing.B) {
    t := Task{ID: 42, Title: "buy milk", Done: false}

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        sinkFmt = FormatTaskBuilder(t)
    }
}

Then you compare the results and no longer “take anyone’s word for it” — not mine, not the internet’s, not the inner voice of the optimizer whispering, “Let us rewrite everything in assembly...” No. Not today.

8. Cheat sheet for the main tools

What it is Where it is used Meaning
func BenchmarkXxx(b *testing.B)
*_test.go
Benchmark entry point
b.N
inside the benchmark
How many iterations the runner requested
b.ResetTimer()
after setup
Do not measure preparation; start measuring from a clean slate
b.StopTimer() / b.StartTimer()
around setup inside iterations
Do not measure preparation “along the way”
-bench=...
go test argument
Which benchmarks to run
-benchtime=...
go test argument
How long to collect statistics (approximately)
sink variable
benchmark code
Prevent the compiler from removing computations

9. Typical mistakes when writing benchmarks

Mistake #1: measuring setup instead of the target operation.
This happens unnoticed: inside the benchmark you generate a large input, read a file, create a huge slice — and all of that honestly gets included in the measurement. The fix is almost always the same: move preparation before the loop and place b.ResetTimer() right before the measured part.

Mistake #2: forgetting to use the result and “measuring emptiness”.
If the result of a computation is not stored anywhere, the compiler has the right to optimize your code so that it becomes lighter than you think. In the end you get nice numbers that describe not your algorithm, but how cleverly the compiler threw away the extra work. The remedy is a sink variable: the result must be written somewhere.

Mistake #3: printing or logging inside the measured loop.
fmt.Println inside for i := 0; i < b.N; i++ turns the benchmark into a measurement of console output speed, not your function. If you want to “look” at what is happening, it is better to make a separate unit test or an Example..., and keep the benchmark as “quiet” as possible.

Mistake #4: comparing benchmark results with different inputs.
One benchmark formats a short string, another a long one; one works with n=10, another with n=100000. Then you conclude, “the second is slower.” Yes, slower, because you gave it more work. For algorithm comparisons, the input must be the same and fixed.

Mistake #5: drawing conclusions from one run and without -benchtime when the difference is small.
When you are chasing a difference of a few percent, system noise can be comparable to the effect. In such cases, a longer measurement via -benchtime and repeated runs help. And sometimes the best conclusion sounds like this: “the difference is insignificant; let us keep the more readable code.”

1
任务
Go SELF, 第 71 级, 课程 3
已锁定
性能放大镜
性能放大镜
1
任务
Go SELF, 第 71 级, 课程 3
已锁定
两个格式化器
两个格式化器
1
任务
Go SELF, 第 71 级, 课程 3
已锁定
公正的排序
公正的排序
1
任务
Go SELF, 第 71 级, 课程 3
已锁定
两种循环风格
两种循环风格
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION