go test -cpuprofile
- Go course
- Advanced
- Lesson 56/68
- 4 min
Learn to profile during tests.
Profiling with tests
Benchmarks are the easiest place to take profiles; adding flags is enough, no extra code needed:
go test -bench=Ayristir -cpuprofile cpu.out -memprofile mem.out ./parser
go tool pprof parser.test cpu.outThe profile covers only the code the benchmark measures; it shows a repeatable scenario, not production traffic.
Other test profiles
-blockprofile records waiting points on channels and locks, and -mutexprofile records lock contention. -trace trace.out produces an event timeline. Adding -run=^$ while profiling keeps normal tests from running and the results clean.
Practice Benchmark function
Run a benchmark from a program with testing.Benchmark: pass a func(b *testing.B) that calls strings.Repeat("go", 100). Print whether the result's N is greater than 0.
Starter code
package main
import (
"fmt"
"strings"
"testing"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"strings"
"testing"
)
func main() {
r := testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
strings.Repeat("go", 100)
}
})
fmt.Println(r.N > 0)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the <code>-benchmem</code> flag add?
- A CPU profile
- Race detection
- Test coverage
- Bytes and allocations per operation Correct answer
Explanation: -benchmem adds B/op and allocs/op columns to the output; it doesn't produce a profile file.
2 Memory profile flag
go test -bench=. ____ mem.out
go test -bench=. -memprofile mem.out
Explanation: -memprofile writes a heap profile to a file during the benchmark.
3 go test flags
| Term | Meaning |
|---|---|
-cpuprofile |
CPU profile |
-memprofile |
Memory profile |
-benchmem |
B/op, allocs/op |
-run=^$ |
Skip tests |