# 基准测试

URL: https://caijiao.org/go/07-test/03-benchmark
Source: docs/go/07-test/03-benchmark.md
Description: 本节介绍 Go 语言中基准测试的用法，帮助评估函数性能，常用于性能优化前的测量。

## 1. 什么是基准测试

基准测试用于衡量代码的性能表现，测试函数执行所需的时间。使用 `testing.B` 类型。

## 2. 编写基准测试函数

函数名以 `Benchmark` 开头，接收 `*testing.B` 参数：

```go
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}
```

## 3. 运行基准测试

使用 `-bench` 标志运行：

```bash
go test -bench=.
```

输出会显示每次操作所用的时间和操作次数。

## 4. 示例输出

```
BenchmarkAdd-8   	1000000000	         0.45 ns/op
```

## 5. 注意事项

- 避免在循环中使用 `fmt.Println` 等耗时操作
- 使用 `b.ResetTimer()` 和 `b.StopTimer()` 控制测试范围

---

基准测试是 Go 标准库 testing 的一部分，是优化代码性能的重要工具。
