Don't guess, measure: your first test and benchmark
Write a test, a table-driven test and subtests with go test, measure speed with b.Loop and -benchmem, and expose a benchmark that lied.
🌐 Oʻzbekcha · Русский · English
Lesson GO-1.07 · Go: 0 → Guru · ▶️ video coming soon · 💻 GitHub
This is the full written version of the video lesson: you can learn from it without watching (or hearing) the video. The video itself is in Uzbek.
What you will learn
We ask the computer one simple question: “Is 2024 a leap year?” A measuring tool says the answer took a few tenths of a nanosecond. A nanosecond is one billionth of a second. At our processor’s top speed, one “step” (a clock cycle) takes about 0.23 nanoseconds. So the answer came in about one cycle. Is it really that fast? This is not proof yet, but it is suspicious. At the end of the lesson we will measure and show: this number is not about leap years at all.
One idea: a test checks that code is correct, a benchmark measures how fast it is. Trust neither of them blindly: don’t guess, measure.
By the end of the lesson you will:
- write a test and a table-driven test with
go test, and run the subtest you need with-vand-run; - read the message of a failed test, find the bug, and after the fix check the whole package again;
- write a benchmark with
b.Loopand read the-benchmemcolumns (ns/op,B/op,allocs/op); - expose a lying benchmark by comparing it with an empty loop.
Today’s three core new words:
| Word | Plain meaning | Term |
|---|---|---|
| test | a small program that asks a function a question and compares its answer with the expected one | test |
| table-driven test | a list with one case per row (name, input, expected answer) and one loop that goes through it | table-driven test |
| benchmark | a function that runs code many times and measures how much time and memory one call takes | benchmark |
Two helper words also appear on the way: subtest (a separate named test for one row of the table) and memory allocation (the program takes a new place in memory for a new value). We explain both where they are needed.
Before you start
- GO-1.06 · Functions: a function takes and returns values; an anonymous function (written in
place,
func(…) { … }); theif s := …; condition {form ofif. - GO-1.05 · Go has no while: one for:
for,range, slice ([]int{…}),_(a value we don’t need),%(remainder of division),switchwith no expression. - GO-1.04 · len(“oʻzbek”) = 7?: rune,
[]rune(s), Unicode number (U+02BB), the kinds of apostrophe and thetozalafunction,Printfverbs (%d,%q). - GO-0.04 · if: the program makes a decision:
if,==,!=,true/false. - GO-0.05 · for: the computer never gets tired of repeating: the counter
i,i++. - Run this lesson’s examples in the course folder, not on go.dev/play :
go testchecks not one file but a whole folder (package), and a benchmark must be measured on your own computer. Open the terminal in the lesson folder (lessons/007-test-bench)../soddameans “thesoddafolder here”. - The commands use a few helper terminal tools; we explain each the first time it appears:
|,grep,column,awk.
First, let’s recall the previous lesson. In port/main.go from GO-1.06, the line
port, err := strconv.Atoi(s) was written inside if, and the server started on port 8080 instead of 9000. Did the
compiler catch this bug?
Answer
No. The program compiled without errors and ran, it just ran wrong. Inside if, := created a new port
(shadowing), and the outer port stayed 8080. The compiler checks only the rules of the language: it does not know
what the program is supposed to do. A linter or a test catches this kind of bug. Today we write a test ourselves.
The plan: correctness first, then speed
Today we answer two questions:
| Stage | Question | Tool |
|---|---|---|
| 1 | Does the function work correctly? | go test (test) |
| 2 | How fast is the function? | go test -bench (benchmark) |
The motto is the same for both: don’t guess, measure.
Your first test
As an example we take the leap year: a year in which February has 29 days. The first attempt is one line: if the
year divides by 4, it is a leap year. This is sodda/kabisa.go (sodda means “simple”, kabisa means “leap”):
package kabisa
// kabisa: yil kabisa yilimi? Birinchi, sodda urinish.
func kabisa(yil int) bool {
return yil%4 == 0
}| Line | Code | What it does |
|---|---|---|
| 1 | package kabisa | this file belongs to the kabisa package. This time it is not main: this is not a standalone program but a set of functions that other code calls |
| 3 | // kabisa: … | a comment, Go does not read it |
| 4 | func kabisa(yil int) bool { | the kabisa function: takes yil (“year”) of type int, returns a bool (true or false) |
| 5 | return yil%4 == 0 | yil % 4 is the remainder after dividing by 4. If the remainder is 0, true, otherwise false |
Is this function correct? So that we don’t check it by hand every time, we write a small program. Think of checking
a calculator: you press 2 + 2 and expect 4. You know the expected answer in advance and compare it with the
calculator’s answer. A small program that asks a function a question and compares its answer with the expected one
is a check, in Go terms a test. This is sodda/kabisa_test.go:
package kabisa
import "testing"
func TestKabisa(t *testing.T) {
if !kabisa(2024) {
t.Errorf("kabisa(2024) = false, kutilgan true")
}
}| Line | Code | What it does |
|---|---|---|
| — | file name kabisa_test.go | the name ends with _test.go. go build does not put such files into the program, but go test finds and runs them |
| 1 | package kabisa | the test lives in the same package, so it can see the kabisa function |
| 3 | import "testing" | the testing package that comes with Go: tools for tests |
| 5 | func TestKabisa(t *testing.T) { | a test function: its name starts with the word Test and it takes t of type testing.T. t is the test’s “remote control”: we report errors through it. The * sign is explained in GO-1.11 |
| 6 | if !kabisa(2024) { | ! means “not”: if kabisa(2024) returns false, we go inside |
| 7 | t.Errorf(…) | writes an error message and marks the test as failed, but does not stop it: the next lines still run. The message is in Uzbek: ”…, expected true” |
t.Errorf does not stop the test. If you need to stop, there is t.Fatalf: it writes the message and ends this test
at once.
Now let’s run it. go test ./sodda means “run the tests in the sodda folder”. Two extras:
-v(“verbose”) prints the name and result of every test;-run TestKabisaselects only the tests whose name matches this pattern. The pattern is a regexp (a template for searching text); the wordTestKabisais not in the nameTestJadval, so that one is not selected.
Predict: A) PASS · B) FAIL · C) a compile error
Answer
A: PASS. If we divide 2024 by 4, the remainder is 0: kabisa(2024) returns true. And !true is false, so
we don’t go inside the if, and t.Errorf is not called. A test that recorded no error is a passed test.
$ go test -v -run TestKabisa ./sodda
=== RUN TestKabisa
--- PASS: TestKabisa (0.00s)
PASS
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/sodda 0.002s| Line | Meaning |
|---|---|
=== RUN TestKabisa | the test started |
--- PASS: TestKabisa (0.00s) | the test passed; the time it took is in brackets |
PASS | all selected tests in the package passed |
ok …/sodda 0.002s | the full package name (the course module name + the folder) and the total time |
The last line may also show (cached) instead of a time. If the code did not change, Go does not run the test again
and takes the previous result from the cache (a place where it was saved). To force a new run, add -count=1.
The test passed. So is the function correct?
Table-driven test: many cases, one loop
One example is not enough. 2024 came out right, but what about other years? Writing a separate test function for each year is long and boring. Think of a school register: one student per row, their data in the columns. We write tests the same way: one case per row — its name, its input and its expected answer. Below it, one loop checks every row. This is the usual way in Go, the table-driven test.
The expected answers in the table come from the Gregorian calendar. Its rule: if a year divides by 4, it is a leap
year; but a year that divides by 100 is a leap year only if it also divides by 400. This is sodda/jadval_test.go
(jadval means “table”):
package kabisa
import "testing"
func TestJadval(t *testing.T) {
jadval := []struct {
nom string
yil int
want bool
}{
{"oddiy", 2026, false},
{"4 ga", 2024, true},
{"100 ga", 1900, false},
{"400 ga", 2000, true},
}
for _, tc := range jadval {
t.Run(tc.nom, func(t *testing.T) {
if got := kabisa(tc.yil); got != tc.want {
t.Errorf("kabisa(%d) = %v, kutilgan %v", tc.yil, got, tc.want)
}
})
}
}| Line | Code | What it does |
|---|---|---|
| 6–10 | jadval := []struct { nom string; yil int; want bool } | says what one row of the table looks like: nom (“name”, text), yil (“year”, number), want (bool, “the expected answer”). A type that groups several named parts (fields) into one value is called a struct; we cover it in GO-1.10. [] means a list of them, that is a slice (GO-1.08) |
| 11–14 | {"oddiy", 2026, false}, … | the four rows of the table: name, year, expected answer (oddiy means “ordinary”, 4 ga means “by 4”) |
| 16 | for _, tc := range jadval { | takes each row in turn into tc (tc stands for “test case”) |
| 17 | t.Run(tc.nom, func(t *testing.T) { | t.Run runs the row as a separate test named tc.nom. The second argument is an anonymous function (GO-1.06): the code that checks this row |
| 18 | if got := kabisa(tc.yil); got != tc.want { | stores the function’s answer in got and compares it with the expected one |
| 19 | t.Errorf("kabisa(%d) = %v, kutilgan %v", …) | a message from a template: the year goes in place of %d, the values of got and want in their plain form (true/false) in place of %v |
A separate test opened by t.Run is called a subtest. Every subtest has its own name and its own result. That
is why the message shows exactly which case failed. If you need a new case, you add one row to the table, and that’s
all: the loop and the check do not change.
How the loop runs:
| Lap | tc.nom | tc.yil | tc.want | kabisa(tc.yil) = got | Subtest |
|---|---|---|---|---|---|
| 1 | oddiy | 2026 | false | ? | TestJadval/oddiy |
| 2 | 4 ga | 2024 | true | ? | TestJadval/4_ga |
| 3 | 100 ga | 1900 | false | ? | TestJadval/100_ga |
| 4 | 400 ga | 2000 | true | ? | TestJadval/400_ga |
A subtest’s full name is the test name, a / and the row name. A space in the name becomes an underscore _.
sodda/kabisa.go still checks only yil%4 == 0. Which subtest fails? A) none · B) 100 ga ·
C) oddiy and 100 ga
Answer
B: 100 ga. Let’s fill in the ? marks: 2026 → remainder 2 → false (expected false, right); 2024 → true
(right); 1900 → dividing 1900 by 4 leaves 0 → true, but false was expected: fails; 2000 → true (right). If
you chose “C”: 2026 does not divide by 4, and the simple function also says false, correctly.
$ go test ./sodda
--- FAIL: TestJadval (0.00s)
--- FAIL: TestJadval/100_ga (0.00s)
jadval_test.go:19: kabisa(1900) = true, kutilgan false
FAIL
FAIL github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/sodda 0.002s
FAILThis time there is no -v: go test stays quiet about passed tests and shows only the failed ones. We read the
message from the bottom up:
jadval_test.go:19:— the message was written in the filejadval_test.go, line 19, int.Errorf;kabisa(1900) = true, kutilgan false— which input, what came out, what was expected (kutilgan means “expected”);--- FAIL: TestJadval/100_ga— which subtest; the space in100 gabecame_;--- FAIL: TestJadval— if one subtest fails, the wholeTestJadvalcounts as failed too;- the last
FAILlines — the package and the whole command ended in failure.
TestKabisa also ran and passed, but without -v it is not shown.
1900: the Gregorian rule and Excel
The rule once more:
| Year | By 4? | By 100? | By 400? | Leap year? |
|---|---|---|---|---|
| 2024 | yes | no | — | ✅ yes |
| 2026 | no | — | — | ❌ no |
| 1900 | yes | yes | no | ❌ no |
| 2000 | yes | yes | yes | ✅ yes |
So a year that divides by 4 is a leap year, but if it divides by 100, it must also divide by 400. That is why 2000 was a leap year and 1900 was not.
This bug exists in well-known programs too. According to Microsoft’s documentation, the spreadsheet program Lotus 1-2-3
treated 1900 as a leap year: this made it easier for the program to handle leap years. Excel, to stay compatible with
it, still keeps this bug today: in Excel, 29 February 1900 still “exists”. A fix would break old calculations: for
example, the WEEKDAY function, which finds the day of the week, would start returning a different answer for some
dates.
The fix, and running one subtest
Let’s write the rule in code. This is another folder, the fixed version: kabisa/. Its tests are the same as in
sodda/, only the function is different. grep is a tool that finds and prints the lines of a file that contain a
given word:
$ grep return kabisa/kabisa.go
return yil%4 == 0 && (yil%100 != 0 || yil%400 == 0)The whole file:
package kabisa
// kabisa: yil kabisa yilimi? Grigorian qoidasi:
// 4 ga boʻlinadi, lekin 100 ga boʻlinsa, 400 ga ham boʻlinishi shart.
func kabisa(yil int) bool {
return yil%4 == 0 && (yil%100 != 0 || yil%400 == 0)
}Line 6 has three parts: && means “and”, || means “or”, != means “is it not equal?”. The part in brackets is
computed first: “does not divide by 100 or divides by 400”.
| Year | yil%4 == 0 | yil%100 != 0 | yil%400 == 0 | Result |
|---|---|---|---|---|
| 2026 | false | — | — | false |
| 2024 | true | true | — | true |
| 1900 | true | false | false | false |
| 2000 | true | false | true | true |
(— means Go does not even compute this part: if the left side of && is false, or the left side of || is
true, the answer is already known.)
First we run only the failed subtest. The slash / in -run Jadval/100 separates the test name from the subtest
name: “among tests with Jadval in the name, the subtest with 100 in the name”.
$ go test -v -run Jadval/100 ./kabisa
=== RUN TestJadval
=== RUN TestJadval/100_ga
--- PASS: TestJadval (0.00s)
--- PASS: TestJadval/100_ga (0.00s)
PASS
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/kabisa 0.002sPASS. But that is not enough: it is easy to fix one case and break another. So we also check the whole package:
$ go test ./kabisa
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/kabisa 0.002sAll ok: both TestKabisa and all four rows of the table passed.
Protecting tozala with a test
Now the promise from GO-1.04. There we wrote the tozala (“clean up”) function, which makes all
kinds of apostrophe the same, and said: “protect it with a test”. This is tozala/tozala.go, the function from
lesson 4 unchanged (only without main):
package tozala
import (
"strings"
"unicode"
)
// 004-darsdagi funksiya, oʻzgarishsiz.
// tozala apostrof turlarini bir xil qiladi:
// o/g dan keyin -> ʻ (U+02BB), boshqa harfdan keyin -> ʼ (U+02BC, tutuq belgisi).
// Faqat harfdan keyin turganlarini oʻzgartiradi: soʻz boshidagi ‘ qoʻshtirnoqqa tegmaydi.
func tozala(s string) string {
r := []rune(s)
for i := 1; i < len(r); i++ {
if !strings.ContainsRune("'`´‘’ʻʼ", r[i]) || !unicode.IsLetter(r[i-1]) {
continue
}
ogdan := strings.ContainsRune("oOgG", r[i-1])
keyingiHarf := i+1 < len(r) && unicode.IsLetter(r[i+1])
soz2 := i >= 2 && unicode.IsLetter(r[i-2]) // o/g soʻz boshida emas
switch {
case ogdan && (keyingiHarf || soz2): // oʻzbek, togʻ
r[i] = 'ʻ'
case keyingiHarf: // maʼno
r[i] = 'ʼ'
}
}
return string(r)
}A short reminder (every line is explained in GO-1.04):
- line 13: turns the text into a list of runes, because a
stringcannot be changed in place; - lines 14–27: an apostrophe after a letter becomes
ʻafter o/g andʼbetween two letters; - line 28: turns the list back into text and returns it.
Its table-driven test, tozala/tozala_test.go:
package tozala
import "testing"
func TestTozala(t *testing.T) {
jadval := []struct {
nom, kirish, want string
}{
{"klaviatura", "O'zbekiston", "Oʻzbekiston"},
{"jingalak", "tog’", "togʻ"},
{"tutuq", "ma'no", "maʼno"},
{"qoshtirnoq", "U ‘Salom’ dedi", "U ‘Salom’ dedi"},
}
for _, tc := range jadval {
t.Run(tc.nom, func(t *testing.T) {
if got := tozala(tc.kirish); got != tc.want {
t.Errorf("tozala(%+q) = %+q, kutilgan %+q", tc.kirish, got, tc.want)
}
})
}
}New lines:
| Line | Code | What it does |
|---|---|---|
| 7 | nom, kirish, want string | all three fields are string (kirish means “input”): fields of the same type can go on one line |
| 9 | {"klaviatura", "O'zbekiston", "Oʻzbekiston"} | the plain keyboard apostrophe ' |
| 10 | {"jingalak", "tog’", "togʻ"} | the curly apostrophe ’ (U+2019) at the end of a word (jingalak means “curly”, togʻ means “mountain”) |
| 11 | {"tutuq", "ma'no", "maʼno"} | a place where the tutuq sign (a separation mark) belongs |
| 12 | {"qoshtirnoq", "U ‘Salom’ dedi", …} | a phrase in quotes (“He said ‘Hello’”): it must not change |
| 17 | t.Errorf("tozala(%+q) = %+q, kutilgan %+q", …) | %+q prints text in quotes, and characters outside ASCII as their Unicode number (’) |
Why %+q? On screen ’ and ʻ look almost the same; the eye cannot tell them apart. %+q writes them as numbers:
’ and ʻ — the difference is visible at once. (ASCII is the Latin letters, digits and simple symbols on
the keyboard; ’ and ʻ are not part of it.)
A fast path, and the pause question
Now let’s speed up tozala. Some texts have no apostrophe at all, for example numbers, codes, or text in Cyrillic
script. Then why turn the whole text into runes? The new tozala checks first: if there is no apostrophe, it returns
the text itself. If there is one, it calls the old function from lesson 4. This is tez/tozala.go (tez means
“fast”):
package tozala
import "strings"
func tozala(s string) string {
if !strings.Contains(s, "'") { // tez yoʻl: apostrof yoʻq
return s
}
return tozalaEski(s)
}| Line | Code | What it does |
|---|---|---|
| 6 | if !strings.Contains(s, "'") { | strings.Contains: is "'" inside s? ! means “if not” |
| 7 | return s | the fast path: returns the text itself, converts nothing |
| 9 | return tozalaEski(s) | otherwise the old function runs (eski means “old”) |
tozalaEski is the tozala from lesson 4 itself, only with another name (in the file tez/eski.go). The tests are
the same four rows from tozala/tozala_test.go.
Question: do all four tests in the table pass? Look at the table rows once more.
A) yes, all four · B) no, jingalak fails · C) no, qoshtirnoq fails
Answer
B: jingalak fails. The fast path looks only for the keyboard apostrophe '. But tog’ has the curly ’, not
'. So the function “thinks” there is no apostrophe and returns the text unchanged. If you chose “C”:
U ‘Salom’ dedi also returns through the fast path, but it must not change anyway, so that test passes.
| Case | Has '? | Which path | Result | Test |
|---|---|---|---|---|
klaviatura | yes | old | Oʻzbekiston | ✅ |
jingalak | no (has ’) | fast | tog’ (unchanged) | ❌ |
tutuq | yes | old | maʼno | ✅ |
qoshtirnoq | no | fast | U ‘Salom’ dedi | ✅ |
We check both folders with one command: the old tozala/ and the new tez/.
$ go test ./tozala ./tez
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/tozala 0.001s
--- FAIL: TestTozala (0.00s)
--- FAIL: TestTozala/jingalak (0.00s)
tozala_test.go:17: tozala("tog’") = "tog’", kutilgan "togʻ"
FAIL
FAIL github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/tez 0.001s
FAILThe old function passed; the fast version failed on the jingalak case. Reading the message: the input is
"tog’", the result is also "tog’", but "togʻ" was expected. ’ is the curly apostrophe,
ʻ is the sign used in oʻ/gʻ. If the message had used plain %q, the screen would show "tog’" and "togʻ":
very hard to tell apart (we will see this in “Common mistakes”).
The eye cannot see this kind of bug, because on screen the characters look almost the same. Without the test it would quietly reach the user.
The fix: strings.ContainsAny
The fix: look for every kind of apostrophe, not just one character. strings.ContainsAny(s, chars) means “is any one
of chars in s?”. This is tezfix/tozala.go:
$ grep ContainsAny tezfix/tozala.go
if !strings.ContainsAny(s, "'`´‘’ʻʼ") { // hech bir turi yoʻqpackage tozala
import "strings"
func tozala(s string) string {
if !strings.ContainsAny(s, "'`´‘’ʻʼ") { // hech bir turi yoʻq
return s
}
return tozalaEski(s)
}"'`´‘’ʻʼ" is exactly the seven characters the old function looks for. Now the fast path runs only when none of
them is present.
$ go test ./tezfix
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/tezfix 0.002sThe tests pass again. This is the main value of a test: you change code freely, and if you break something, you know at once.
Benchmark: measuring speed
Did it get faster? We don’t guess, we measure. One call is too short to time with a clock. Think of a race: you cannot time one step with a stopwatch, but you can time a million steps and divide the time by the number of steps. A function that runs code many times like this and works out how long one call took is a speed measurement, in Go terms a benchmark.
A benchmark is also written in a test file. This is tezfix/bench_test.go:
package tozala
import "testing"
var matnlar = []struct{ nom, s string }{
{"toza", "Bugun havo yaxshi, darsdan keyin bozorga boramiz"},
{"apostrof", "Oʻzbekiston togʻlari, maʼno va qoʻshiq"},
}
func BenchmarkEski(b *testing.B) {
for _, m := range matnlar {
b.Run(m.nom, func(b *testing.B) {
for b.Loop() {
tozalaEski(m.s)
}
})
}
}
func BenchmarkTez(b *testing.B) {
for _, m := range matnlar {
b.Run(m.nom, func(b *testing.B) {
for b.Loop() {
tozala(m.s)
}
})
}
}| Line | Code | What it does |
|---|---|---|
| 5–8 | var matnlar = []struct{ nom, s string }{…} | two texts (matnlar means “texts”): toza (“clean”) has no apostrophes, apostrof has them. Declared with var outside any function, so both benchmarks can see them |
| 10 | func BenchmarkEski(b *testing.B) { | a benchmark function: its name starts with Benchmark and it takes b of type testing.B |
| 11 | for _, m := range matnlar { | for each text |
| 12 | b.Run(m.nom, func(b *testing.B) { | like t.Run: opens a separate, named benchmark for each text (BenchmarkEski/toza, BenchmarkEski/apostrof) |
| 13 | for b.Loop() { | the measured loop. b.Loop() asks Go “one more lap?”: Go returns true until it has done enough laps, then false |
| 14 | tozalaEski(m.s) | the code being measured: the old function |
| 20–28 | func BenchmarkTez… | the same, but with the new tozala |
How many times does Go run the loop? As many as needed: usually until the measurement adds up to one second, but at most one billion (1 000 000 000) times.
Reading the result: ns/op, B/op and allocs/op
Let’s run it. The command is long, so we split it into parts:
| Part | Meaning |
|---|---|
go test -bench . | run the benchmarks too; . means “any name”, that is all of them |
-benchmem | measure memory as well as time |
./tezfix | in the tezfix folder |
| grep ns/op | | (a pipe) passes the output of the command on the left to the one on the right; grep keeps only the lines with ns/op, the result lines |
| column -t | lines the rows up in columns so they are easy to read |
We need one new idea. The old tozala makes a new list ([]rune(s)) and a new text (string(r)) on every call. For
them the program takes a new place in memory, as if it tore a fresh page out of a notebook every time. This is called
memory allocation. It takes time, and later Go also has to clean up the places nobody uses any more.
Predict: on the toza text without apostrophes, how many times per call does the fast version allocate memory?
A) 0 · B) 1 · C) 2
Answer
A: 0. There is no apostrophe, so the fast path returns s itself: neither a new list nor a new text is made. If
you chose “C”, you were thinking of the old function: it makes []rune(s) and string(r) every time.
$ go test -bench . -benchmem ./tezfix | grep ns/op | column -t
BenchmarkEski/toza-12 1908316 602.0 ns/op 256 B/op 2 allocs/op
BenchmarkEski/apostrof-12 1954908 619.8 ns/op 208 B/op 2 allocs/op
BenchmarkTez/toza-12 4480161 232.1 ns/op 0 B/op 0 allocs/op
BenchmarkTez/apostrof-12 1784139 694.1 ns/op 208 B/op 2 allocs/opThe columns (using the first row):
| Column | Value | Meaning |
|---|---|---|
| name | BenchmarkEski/toza-12 | the benchmark and text name; -12 is how many processor cores Go may use at the same time (12 on this computer) |
| laps | 1908316 | how many times the b.Loop loop ran |
ns/op | 602.0 | time per call in nanoseconds (“op” = operation, one call) |
B/op | 256 | bytes allocated per call |
allocs/op | 2 | number of memory allocations per call |
What we saw:
- On a text of this length, the old version allocates memory twice per call: for the list of runes and for the new text. (On a very short text, up to 32 runes, no separate place is allocated for the list, so it is once.)
- On the text without apostrophes, the fast version does not allocate at all and in our run it is about 2.6 times faster (602.0 vs 232.1 ns). In the measurements made while preparing the lesson the difference was 2.4–2.9 times: roughly two to three times.
- On the text with apostrophes there is no gain: both allocate twice, 208 bytes each. The fast version first
searches with
ContainsAnyand then calls the old function anyway. In our run it even came out a little slower; in the measurement made while preparing the lesson the two were equal (437 and 438 ns). A small difference like this is noise.
Uzbek text has an apostrophe in almost every sentence: in the narration of this lesson’s own video, in two sentences
out of three (75 out of 108). So this speed-up does not help everywhere. Nanoseconds change a little every time, but
the number of allocations (allocs/op) and B/op do not.
The benchmark lied: comparing with an empty loop
Now back to the mystery from the start. This is kabisa/bn_test.go. It has two old-style benchmarks: this is how
benchmarks were written before b.Loop. Both are a plain for loop that counts up to b.N. b.N is the number of
laps Go chose.
package kabisa
import "testing"
func BenchmarkBoshBN(b *testing.B) {
for i := 0; i < b.N; i++ {
}
}
func BenchmarkKabisaBN(b *testing.B) {
for i := 0; i < b.N; i++ {
kabisa(i)
}
}| Line | Code | What it does |
|---|---|---|
| 5–8 | BenchmarkBoshBN | an empty loop (bosh means “empty”): counts i from 0 to b.N and does nothing |
| 10–14 | BenchmarkKabisaBN | the same loop, but every lap calls kabisa(i). Its result is never used |
The number we saw at the start came from KabisaBN. Here it is:
$ go test -bench KabisaBN ./kabisa | grep ns/op
BenchmarkKabisaBN-12 1000000000 0.2267 ns/opThe loop ran exactly one billion times (Go’s upper limit), and one call took 0.23 ns. On this computer one cycle is
about 0.23 ns: the top frequency is 4.4 GHz. This is not proof yet: a processor can run a simple loop even faster than
one cycle. For proof we run both benchmarks side by side (-bench BN means every benchmark with BN in its name).
Predict: A) KabisaBN is several times slower than the empty loop · B) the two are almost the same ·
C) the empty loop is slower
Answer
B: almost the same. If the leap-year check (three divisions, comparisons) were really done, KabisaBN would be
clearly slower. The same time means both loops do the same work, so the leap year is not computed at all. “A” is the
answer we expected, but we were fooled.
$ go test -bench BN ./kabisa | grep ns/op
BenchmarkBoshBN-12 1000000000 0.1831 ns/op
BenchmarkKabisaBN-12 1000000000 0.2118 ns/opA benchmark can lie. Here is the proof: the loop that calls kabisa showed almost the same time as the empty loop
(0.18 and 0.21 ns; in the measurements made while preparing the lesson the difference was 7–20 %). So it measured not
the leap year but doing nothing.
Let’s look at the machine code the compiler produced. The command has two parts (&& means “if the first one
succeeds, run the second”):
go test -c -o k.test ./kabisadoes not run the tests; it only compiles them into a program filek.test;go tool objdump -s 'KabisaBN$' k.testprints, from that file, the machine code (processor instructions) of the function whose name ends withKabisaBN;awk 'NR>1 {print $4, $5, $6}'skips the header line and keeps only the 4th, 5th and 6th word of each line, that is the instruction itself.
$ go test -c -o k.test ./kabisa && go tool objdump -s 'KabisaBN$' k.test | awk 'NR>1 {print $4, $5, $6}'
XORL CX, CX
JMP 0x52e8c7
INCQ CX
CMPQ 0x210(AX), CX
JG 0x52e8c4
RET | Instruction | Meaning | Part in Go |
|---|---|---|
XORL CX, CX | set register CX (a cell inside the processor) to 0 | i := 0 |
JMP … | jump to the check | — |
INCQ CX | add 1 to CX | i++ |
CMPQ 0x210(AX), CX | compare CX with b.N | i < b.N |
JG … | if b.N is greater, go back to INCQ | the loop goes on |
RET | leave the function | — |
The loop holds only the counter: add, compare, go back. Nothing is left of the leap-year check (%4, %100, %400).
The machine code of BenchmarkBoshBN is exactly the same six instructions (only the addresses differ).
The cause comes in two steps. First, the compiler inlines the small function: instead of calling it, it copies its body (the code inside) to the place of the call. Second, it sees that the result is never used and deletes the computation completely. Think of a cook who does not even cook a dish that nobody will eat. The compiler does this to make programs faster, but our measurement was left empty.
b.Loop: keeping the result alive
b.Loop, added in Go 1.24, fixes this: it keeps the arguments and results of calls inside the loop “alive”, so the
compiler cannot delete them as unneeded. This is kabisa/loop_test.go: the same two benchmarks, but with b.Loop:
package kabisa
import "testing"
func BenchmarkBoshLoop(b *testing.B) {
yil := 0
for b.Loop() {
yil++
}
}
func BenchmarkKabisaLoop(b *testing.B) {
yil := 0
for b.Loop() {
kabisa(yil)
yil++
}
}| Line | Code | What it does |
|---|---|---|
| 5–10 | BenchmarkBoshLoop | an “empty” loop: only increases yil. To keep the comparison fair, it also has yil++ |
| 13 | yil := 0 | the year is created once, before the loop |
| 15 | kabisa(yil) | called on every lap; b.Loop keeps its argument and result |
| 16 | yil++ | the year changes on every lap |
In both, the year changes on every lap. What will the result be?
$ go test -bench Loop ./kabisa | grep ns/op
BenchmarkBoshLoop-12 1000000000 0.7043 ns/op
BenchmarkKabisaLoop-12 850859284 1.331 ns/op- The empty
b.Looploop itself also takes a little time (0.70 ns here). This is the cost of measuring: on every lapb.Loopchecks its own counter. - The leap-year loop is about twice as slow (1.33 ns, 1.9 times; 1.7–2.1 times in the course README), because now
the real computation is done. The work of
kabisaitself is the difference between the two numbers.
| Benchmark | What is left in the loop | ns/op (ours) |
|---|---|---|
BoshBN | only the counter | 0.18 |
KabisaBN | only the counter (kabisa deleted) | 0.21 |
BoshLoop | b.Loop counter + yil++ | 0.70 |
KabisaLoop | b.Loop counter + yil++ + the leap-year check | 1.33 |
One subtle point: b.Loop keeps the result, but it does not stop the compiler from computing it in advance. If you
pass a constant number, for example kabisa(2024), the answer is ready at compile time. That is why in our benchmarks
the year changes on every lap. The experiment is below, in the “Going deeper” section.
Don’t trust a single measurement
The last rule: don’t trust a single measurement. Even the same benchmark gives a slightly different result each time,
especially when the computer is busy with other work. We saw this ourselves: BenchmarkEski/toza on this page showed
602 ns (the computer was busy), while during the lesson’s preparation (2026-11-25) it was 437 ns. The number of
allocations was 2 both times.
When you compare two versions:
| Rule | How |
|---|---|
| at least 10 times | -count 10 runs each benchmark 10 times |
| look at the statistics | the benchstat program compares two files and tells you whether a difference is real or random |
| if it is suspiciously fast | as today, compare with an empty loop |
The workflow from the course README (benchstat is installed separately; it was not run for this page):
go install golang.org/x/perf/cmd/benchstat@latest
go test -run '^$' -bench . -benchmem -count 10 ./tezfix > eski.txt # oʻzgarishdan oldin
# ... kodni oʻzgartiring ...
go test -run '^$' -bench . -benchmem -count 10 ./tezfix > yangi.txt # keyin
benchstat eski.txt yangi.txt-run '^$'is a pattern that matches no test: only the benchmarks run, not the tests;> eski.txtwrites the output to a file instead of the screen (eski means “old”, yangi means “new”; the code comments say “before the change”, “change the code”, “after”);benchstatgives, for each benchmark, the median (the middle value) and a confidence interval; the~sign means “no statistical difference”.
“Running it again and again until you like the result” is also a mistake: that way you take random luck for a real difference.
Today we saw: a test checks correctness, a benchmark measures speed, and neither should be trusted blindly. In the
next lesson, GO-1.08 · Slices: the append trap, we will see how append grows and measure it
ourselves, just like today.
Going deeper (optional): b.Loop is not magic either
The video gives this section one sentence; the experiment is in the course folder doimiy/ (doimiy means
“constant”). This is doimiy/bench_test.go (doimiy/kabisa.go is the same as kabisa/kabisa.go):
package kabisa
import "testing"
// Tajriba (README): doimiy argument. Go 1.26 kabisa'ni inline qilib,
// kabisa(2024) = true javobini kompilyatsiya paytida hisoblaydi.
// b.Loop natijani "tirik" saqlaydi, lekin hisobning oʻzi siklda qolmaydi.
func BenchmarkDoimiyLoop(b *testing.B) {
for b.Loop() {
kabisa(2024)
}
}
// Har aylanishda boshqa yil: hisob haqiqatan bajariladi.
func BenchmarkKabisaLoop(b *testing.B) {
yil := 0
for b.Loop() {
kabisa(yil)
yil++
}
}How do we know whether the leap-year check is in the machine code? Go computes % 100 not by division but by a faster
multiplication (the IMULQ instruction). So if there is an IMULQ, there is a computation. grep -c prints the
number of matching lines.
$ go test -c -o d.test ./doimiyThis command printed nothing: it only created the file d.test.
$ go tool objdump -s 'BenchmarkDoimiyLoop$' d.test | grep -c IMULQ
0$ go tool objdump -s 'BenchmarkKabisaLoop$' d.test | grep -c IMULQ
1DoimiyLoop has no computation: Go 1.26.8 worked out kabisa(2024) = true at compile time, and the loop only stores
the ready true. KabisaLoop does have the computation. b.Loop keeps the result alive, but it does not forbid
computing it in advance.
Two more facts:
- In Go 1.24,
b.Loopprevented inlining inside the loop. Go 1.26 removed that ban, and the argument and result are kept withruntime.KeepAlive. We tested only Go 1.26.8; on 1.24 this experiment may give a different result. - Setup code before
b.Loop(for example, preparing large data) runs only once and is not counted in the time:b.Loopcontrols the timer itself. In the oldb.Nstyle, the benchmark function was called several times.
Common mistakes
1. “The test passed, so the code is correct.” The main trap of this lesson. TestKabisa passed with 2024, but
the function was wrong for 1900 (we saw it in the “Table-driven test” section). A test checks only the questions you
asked. Fix: add the edge cases to the table too: years divisible by 100 and by 400, an empty text, every kind of
apostrophe.
2. An old-style benchmark whose result is never used. for i := 0; i < b.N; i++ { kabisa(i) } measures an empty
loop, not the leap year: the compiler deletes the computation (above, in “The benchmark lied”). There is no error
message, only a suspiciously small number. Fix: write for b.Loop() { … } and compare with an empty loop.
3. The test file name does not end with _test.go. This example is not in the course folder; it was run in a
separate module. The nomi/ folder holds sodda/kabisa.go and a file named kabisatest.go (no underscore):
package kabisa
import "testing"
func TestKabisa(t *testing.T) {
if !kabisa(2024) {
t.Errorf("kabisa(2024) = false, kutilgan true")
}
}$ go test ./nomi
? xatolar/nomi [no test files]no test files: go test looks for tests only in files whose name ends with _test.go. Worse: kabisatest.go is
now an ordinary file, and the testing package ended up inside the program itself. Fix: name the file
kabisa_test.go.
4. A lowercase letter after Test. (Not in the course folder.) Testkabisa was written instead of TestKabisa:
package kabisa
import "testing"
func Testkabisa(t *testing.T) {
if !kabisa(2024) {
t.Errorf("kabisa(2024) = false, kutilgan true")
}
}$ go test ./harf
# xatolar/harf
# [xatolar/harf]
harf/kabisa_test.go:5:6: Testkabisa has malformed name: first letter after 'Test' must not be lowercase
FAIL xatolar/harf [build failed]
FAILharf/kabisa_test.go, line 5, column 6: Testkabisa has malformed name: first letter after ‘Test’ must not be
lowercase. This error was found not by the compiler but by go vet: before the tests, go test itself runs a part
of the go vet checks. Fix: TestKabisa.
5. A forgotten argument in the Errorf template. (Not in the course folder.) The template has %d (the year) and
%v, but the year is not passed:
package kabisa
import "testing"
func TestKabisa(t *testing.T) {
if got := kabisa(1900); got {
t.Errorf("kabisa(%d) = %v, kutilgan false", got)
}
}$ go test ./format
# xatolar/format
# [xatolar/format]
format/kabisa_test.go:7:20: (*testing.common).Errorf format %d has arg got of wrong type bool
FAIL xatolar/format [build failed]
FAILErrorf format %d has arg got of wrong type bool: the %d in the Errorf template received the argument got,
which has the wrong type, bool. %d expected a number, but got ended up as the first argument. go vet found
this too, and the test did not run at all (build failed). Fix:
t.Errorf("kabisa(%d) = %v, kutilgan false", 1900, got).
6. No pattern after -bench. -bench always needs a pattern after it, for example .:
$ go test -bench ./tezfix
# .
no Go files in /home/haywan/Developer/go-backend-uz/lessons/007-test-bench
FAIL . [setup failed]Go read ./tezfix not as a folder but as the pattern for -bench. No folder was given, so it tried to check the
current folder: no Go files in …. Fix: go test -bench . ./tezfix.
7. %q instead of %+q in the message. (Not in the course folder.) A copy of the tez/ folder, only line 17 of
tozala_test.go has %q instead of %+q:
package tozala
import "testing"
func TestTozala(t *testing.T) {
jadval := []struct {
nom, kirish, want string
}{
{"klaviatura", "O'zbekiston", "Oʻzbekiston"},
{"jingalak", "tog’", "togʻ"},
{"tutuq", "ma'no", "maʼno"},
{"qoshtirnoq", "U ‘Salom’ dedi", "U ‘Salom’ dedi"},
}
for _, tc := range jadval {
t.Run(tc.nom, func(t *testing.T) {
if got := tozala(tc.kirish); got != tc.want {
t.Errorf("tozala(%q) = %q, kutilgan %q", tc.kirish, got, tc.want)
}
})
}
}$ go test ./qbelgi
--- FAIL: TestTozala (0.00s)
--- FAIL: TestTozala/jingalak (0.00s)
tozala_test.go:17: tozala("tog’") = "tog’", kutilgan "togʻ"
FAIL
FAIL xatolar/qbelgi 0.001s
FAILThe test failed correctly, but the message is hard to read: "tog’" and "togʻ" look almost the same on screen.
Fix: use %+q wherever look-alike characters may appear.
(Examples 3–7 were all run in one separate module, go 1.26.)
Check yourself
Answer first, then open.
1. Does go build put test files into the program? How is a test file recognised?
Answer
It does not. Files whose name ends with _test.go are found and run only by go test. A test function’s name starts
with Test, a benchmark’s with Benchmark.
2. Does a test stop after t.Errorf is called?
Answer
No. t.Errorf records the error and marks the test as failed, but the next lines keep running. To stop at once there
is t.Fatalf.
3. How many subtests does this command run? A) 1 · B) 3 · C) 4
go test -v -run Jadval/ga ./kabisaAnswer
B: 3. The ga after / is a pattern; it can be anywhere in the name: 4_ga, 100_ga, 400_ga. oddiy has no
ga.
$ go test -v -run Jadval/ga ./kabisa
=== RUN TestJadval
=== RUN TestJadval/4_ga
=== RUN TestJadval/100_ga
=== RUN TestJadval/400_ga
--- PASS: TestJadval (0.00s)
--- PASS: TestJadval/4_ga (0.00s)
--- PASS: TestJadval/100_ga (0.00s)
--- PASS: TestJadval/400_ga (0.00s)
PASS
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/kabisa 0.002s4. A benchmark showed 0.2 ns per call, and the loop ran exactly 1 000 000 000 times. What do you do first?
Answer
I compare it with an empty loop. If the time is almost the same, the compiler deleted the computation being measured.
Then I rewrite the benchmark with for b.Loop() { … } and make sure the argument changes on every lap.
5. The allocs/op column shows 2, the ns/op column shows 602.0. Which number can change if you run it
again?
Answer
ns/op (and the lap count). Time depends on how busy the computer is, while the number of allocations depends on the
code and does not change. So draw conclusions not from one measurement but from at least 10, with benchstat.
6. From GO-1.05: when for _, tc := range jadval walks over jadval, what is tc: the table
row itself or a copy of it?
Answer
A copy. On each step range writes a copy of the element into tc. In the test we only read tc, so there is no
problem here. And since Go 1.22, every iteration gets a new tc, so the anonymous function inside t.Run sees its own
row each time.
Homework
Tasks at four levels. All files are in the lesson folder on GitHub: lessons/007-test-bench . Answers: the homework/ folder. Try it yourself first.
🟢 Easy: add the years 2100 and 2400 to the kabisa table.
Answer
homework/oson/jadval_test.go: two rows are added to the table (the comments say “divides by 100, not by 400” and
“divides by 400”):
{"2100", 2100, false}, // 100 ga boʻlinadi, 400 ga yoʻq
{"2400", 2400, true}, // 400 ga boʻlinadi$ go test -v ./homework/oson
=== RUN TestJadval
=== RUN TestJadval/oddiy
=== RUN TestJadval/4_ga
=== RUN TestJadval/100_ga
=== RUN TestJadval/400_ga
=== RUN TestJadval/2100
=== RUN TestJadval/2400
--- PASS: TestJadval (0.00s)
--- PASS: TestJadval/oddiy (0.00s)
--- PASS: TestJadval/4_ga (0.00s)
--- PASS: TestJadval/100_ga (0.00s)
--- PASS: TestJadval/400_ga (0.00s)
--- PASS: TestJadval/2100 (0.00s)
--- PASS: TestJadval/2400 (0.00s)
PASS
ok github.com/abdurahmon27/go-backend-uz/lessons/007-test-bench/homework/oson 0.003s🟡 Medium: measure the fast path too: instead of ContainsAny, check the bytes with a plain loop and compare the
results.
Answer
homework/bayt/tozala.go. Every apostrophe except ' and ` starts in UTF-8 with a byte greater than 0x80.
So a plain loop over the bytes is enough: when such a byte appears, we switch to the slow path.
for i := 0; i < len(s); i++ {
if c := s[i]; c == '\'' || c == '`' || c >= 0x80 {
return tozalaEski(s)
}
}
return s$ go test -bench . -benchmem ./homework/bayt | grep ns/op | column -t
BenchmarkContainsAny-12 4081128 295.7 ns/op 0 B/op 0 allocs/op
BenchmarkBayt-12 21444952 48.22 ns/op 0 B/op 0 allocs/opThe byte loop is about 6 times faster for us (≈4.5 times in the README’s measurement), neither version allocates
memory, and the tests pass. With a set of non-ASCII characters, ContainsAny checks the text rune by rune, so it is
slower. The price: Cyrillic text (its bytes are above 0x80) now also goes down the slow path. Every speed-up has its
limits, which is why we measure.
🟠 Hard: fix the old-style benchmark without b.Loop: write the result into a package-level variable.
Answer
homework/qiyin/bench_test.go (natija means “result”):
var natija bool
func BenchmarkSinkBN(b *testing.B) {
for i := 0; i < b.N; i++ {
natija = kabisa(i)
}
}The result is written into a variable outside the function, which could be seen from somewhere else. So the compiler cannot delete the computation.
$ go test -bench . ./homework/qiyin | grep ns/op
BenchmarkKabisaBN-12 1000000000 0.2126 ns/op
BenchmarkSinkBN-12 1000000000 0.7216 ns/op
BenchmarkKabisaLoop-12 904552358 1.478 ns/opSinkBN is clearly slower than the empty loop (KabisaBN): the computation now runs. This is the method Dave Cheney
recommended in 2013; today b.Loop is better.
🔴 Guru: change the old tozala so that it does not create a new string when nothing in the text changes, and
prove it with -benchmem.
Answer
homework/guru/tozala.go: an ozgardi (“changed”) flag. Before each replacement it checks whether the new character
differs from the old one; if it does, ozgardi = true. At the end:
if !ozgardi {
return s
}
return string(r)$ go test -bench . -benchmem ./homework/guru | grep ns/op | column -t
BenchmarkEski-12 1788066 670.5 ns/op 208 B/op 2 allocs/op
BenchmarkGuru-12 2658028 467.1 ns/op 160 B/op 1 allocs/opOn a text whose apostrophes are already correct (Oʻzbekiston togʻlari, maʼno va qoʻshiq), allocations dropped from 2
to 1 (only []rune is left), and 208 bytes to 160. The tests pass (go test ./homework/guru).
Sources
- pkg.go.dev/testing :
TestXxx,BenchmarkXxx,_test.go,B.Loop, subtests go help testflag:-run,-bench,-benchmem,-count,-benchtime;go help test: test caching- Go wiki: TableDrivenTests (
t.Errorfdoes not stop the test); M. van Lohuizen, Using Subtests and Sub-benchmarks (Go blog, 2016) - Go source: testing/match.go (a space in a subtest name →
_), testing/benchmark.go (b.N < 1e9,B.Loopandruntime.KeepAlive) - pkg.go.dev/fmt (
%+q), strings.ContainsAny - J. Shao, More predictable benchmarking with testing.B.Loop (Go blog, 2025): “CPUs are fast, but not that fast!”
- Go 1.24 Release Notes: testing (
b.Loop), Go 1.26 Release Notes (b.Loopno longer prevents inlining), golang/go#61515 (proposal), #73137 - Dave Cheney: How to write benchmarks in Go (2013), High Performance Go Workshop
- benchstat (run at least 10 times)
- Microsoft: Excel incorrectly assumes that the year 1900 is a leap year
- All results from
go1.26.8 linux/amd64, Intel Core i5-12450H (top frequency 4.4 GHz), 2026-11-26. Nanoseconds change every run; the README numbers come from measurements on 2026-11-25.
Video and code
▶️ The video is coming soon. This page teaches the whole lesson, so you don’t have to wait for it.
💻 Code and homework answers on GitHub
← Previous lesson: GO-1.06 · Next lesson: GO-1.08 → · All lessons
comments