bench

package
v0.5.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package bench 提供 Hexagon AI Agent 框架的基准测试工具

Bench 用于性能基准测试:

  • BenchmarkRunner: 基准测试运行器
  • BenchmarkReport: 基准测试报告
  • 预定义基准测试

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatReport

func FormatReport(report *BenchmarkReport) string

FormatReport 格式化报告

func HasRegression

func HasRegression(results []RegressionResult) bool

HasRegression 检查结果中是否有回归

Types

type Baseline

type Baseline struct {
	// Name 测试名称
	Name string `json:"name"`

	// AvgNs 平均耗时(纳秒)
	AvgNs float64 `json:"avg_ns"`

	// P99Ns P99 耗时(纳秒)
	P99Ns float64 `json:"p99_ns"`

	// AllocsOp 每次操作分配次数
	AllocsOp int64 `json:"allocs_op"`

	// BytesOp 每次操作分配字节
	BytesOp int64 `json:"bytes_op"`

	// Timestamp 基线记录时间
	Timestamp time.Time `json:"timestamp"`
}

Baseline 性能基线

记录某个基准测试在某一时间点的性能数据,用于后续的回归对比。

type Benchmark

type Benchmark struct {
	// Name 测试名称
	Name string

	// Description 描述
	Description string

	// Fn 测试函数
	Fn BenchmarkFunc

	// Setup 测试前准备函数
	Setup func() error

	// Teardown 测试后清理函数
	Teardown func() error
}

Benchmark 基准测试

func NopBenchmark

func NopBenchmark() Benchmark

NopBenchmark 空操作基准测试(用于测量基线开销)

func SimpleBenchmark

func SimpleBenchmark(name string, fn BenchmarkFunc) Benchmark

SimpleBenchmark 创建简单基准测试

func SleepBenchmark

func SleepBenchmark(d time.Duration) Benchmark

SleepBenchmark 睡眠基准测试(用于验证计时)

type BenchmarkFunc

type BenchmarkFunc func(ctx context.Context) error

BenchmarkFunc 基准测试函数

type BenchmarkReport

type BenchmarkReport struct {
	// Name 报告名称
	Name string `json:"name"`

	// Results 测试结果列表
	Results []BenchmarkResult `json:"results"`

	// StartTime 开始时间
	StartTime time.Time `json:"start_time"`

	// EndTime 结束时间
	EndTime time.Time `json:"end_time"`

	// TotalDuration 总耗时
	TotalDuration time.Duration `json:"total_duration"`

	// Environment 环境信息
	Environment map[string]string `json:"environment"`
}

BenchmarkReport 基准测试报告

type BenchmarkResult

type BenchmarkResult struct {
	// Name 测试名称
	Name string `json:"name"`

	// Iterations 迭代次数
	Iterations int `json:"iterations"`

	// TotalDuration 总耗时
	TotalDuration time.Duration `json:"total_duration"`

	// AvgDuration 平均耗时
	AvgDuration time.Duration `json:"avg_duration"`

	// MinDuration 最小耗时
	MinDuration time.Duration `json:"min_duration"`

	// MaxDuration 最大耗时
	MaxDuration time.Duration `json:"max_duration"`

	// P50 P50 延迟
	P50 time.Duration `json:"p50"`

	// P95 P95 延迟
	P95 time.Duration `json:"p95"`

	// P99 P99 延迟
	P99 time.Duration `json:"p99"`

	// OpsPerSecond 每秒操作数
	OpsPerSecond float64 `json:"ops_per_second"`

	// Errors 错误数
	Errors int `json:"errors"`

	// MemAllocs 内存分配次数
	MemAllocs uint64 `json:"mem_allocs"`

	// MemBytes 内存分配字节数
	MemBytes uint64 `json:"mem_bytes"`
}

BenchmarkResult 基准测试结果

type RegressionDetector

type RegressionDetector struct {
	// contains filtered or unexported fields
}

RegressionDetector 性能回归检测器

对比当前基准测试结果与历史基线,检测性能退化。 支持多维度对比(耗时、分配次数、分配字节),超过阈值即判定为回归。

使用示例:

detector := NewRegressionDetector("baselines.json", WithThreshold(0.1))
_ = detector.LoadBaseline()
results, _ := detector.Check(benchResults)
fmt.Println(detector.Report(results))

func NewRegressionDetector

func NewRegressionDetector(baselinePath string, opts ...RegressionOption) *RegressionDetector

NewRegressionDetector 创建性能回归检测器

baselinePath 为基线文件的存储路径(JSON 格式)。 默认回归阈值为 10%(0.1),可通过选项覆盖。

func (*RegressionDetector) Check

func (d *RegressionDetector) Check(results []*BenchmarkResult) ([]RegressionResult, error)

Check 对比当前结果与历史基线,检测性能回归

对每个基准测试结果,分别检查平均耗时、P99 耗时、分配次数和分配字节数。 任意一项超过阈值即判定为回归。 如果没有对应的历史基线,跳过该测试(不视为回归)。

func (*RegressionDetector) LoadBaseline

func (d *RegressionDetector) LoadBaseline() error

LoadBaseline 从文件加载历史基线

如果文件不存在,返回 nil(不视为错误,因为首次运行时没有基线)。

func (*RegressionDetector) Report

func (d *RegressionDetector) Report(results []RegressionResult) string

Report 生成人类可读的回归检测报告

func (*RegressionDetector) SaveBaseline

func (d *RegressionDetector) SaveBaseline(results []*BenchmarkResult) error

SaveBaseline 保存当前基准测试结果为基线

将 BenchmarkResult 转换为 Baseline 并以 JSON 格式保存到文件。 如果目标目录不存在,会自动创建。

type RegressionOption

type RegressionOption func(*RegressionDetector)

RegressionOption 回归检测器配置选项

func WithAllocsThreshold

func WithAllocsThreshold(threshold float64) RegressionOption

WithAllocsThreshold 单独设置内存分配次数的回归阈值

func WithBytesThreshold

func WithBytesThreshold(threshold float64) RegressionOption

WithBytesThreshold 单独设置内存分配字节数的回归阈值

func WithThreshold

func WithThreshold(threshold float64) RegressionOption

WithThreshold 设置回归阈值百分比

threshold 为百分比,如 0.1 表示 10%,即当性能下降超过 10% 时判定为回归。 同时会设置 allocsThreshold 和 bytesThreshold 为相同值。

type RegressionResult

type RegressionResult struct {
	// Name 测试名称
	Name string `json:"name"`

	// Regressed 是否发生回归
	Regressed bool `json:"regressed"`

	// Current 当前测试结果
	Current *Baseline `json:"current"`

	// Previous 历史基线
	Previous *Baseline `json:"previous"`

	// DeltaPct 平均耗时变化百分比(正数表示变慢,负数表示变快)
	DeltaPct float64 `json:"delta_pct"`

	// Detail 详细说明
	Detail string `json:"detail"`
}

RegressionResult 回归检测结果

描述单个基准测试的回归检测结果,包括是否发生回归以及详细的变化信息。

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner 基准测试运行器

func NewRunner

func NewRunner(opts ...RunnerOption) *Runner

NewRunner 创建基准测试运行器

func (*Runner) Add

func (r *Runner) Add(b Benchmark) *Runner

Add 添加基准测试

func (*Runner) Run

func (r *Runner) Run(ctx context.Context) (*BenchmarkReport, error)

Run 运行所有基准测试

type RunnerOption

type RunnerOption func(*Runner)

RunnerOption 运行器选项

func WithConcurrency

func WithConcurrency(n int) RunnerOption

WithConcurrency 设置并发数

func WithIterations

func WithIterations(n int) RunnerOption

WithIterations 设置迭代次数

func WithTimeout

func WithTimeout(d time.Duration) RunnerOption

WithTimeout 设置超时时间

func WithWarmup

func WithWarmup(n int) RunnerOption

WithWarmup 设置预热次数

type StressOption

type StressOption func(*StressTest)

StressOption 压力测试配置选项

func WithStressConcurrency

func WithStressConcurrency(n int) StressOption

WithStressConcurrency 设置并发数

func WithStressDuration

func WithStressDuration(d time.Duration) StressOption

WithStressDuration 设置持续时间

func WithStressRampUp

func WithStressRampUp(d time.Duration) StressOption

WithStressRampUp 设置升温时间

在升温阶段,并发数会从 1 逐步增加到目标并发数。 升温时间不应超过总持续时间。

type StressResult

type StressResult struct {
	// Name 测试名称
	Name string `json:"name"`

	// TotalOps 总操作数
	TotalOps int64 `json:"total_ops"`

	// SuccessOps 成功操作数
	SuccessOps int64 `json:"success_ops"`

	// FailedOps 失败操作数
	FailedOps int64 `json:"failed_ops"`

	// OpsPerSecond 每秒操作数
	OpsPerSecond float64 `json:"ops_per_second"`

	// AvgLatency 平均延迟
	AvgLatency time.Duration `json:"avg_latency"`

	// P50Latency P50 延迟
	P50Latency time.Duration `json:"p50_latency"`

	// P95Latency P95 延迟
	P95Latency time.Duration `json:"p95_latency"`

	// P99Latency P99 延迟
	P99Latency time.Duration `json:"p99_latency"`

	// MaxLatency 最大延迟
	MaxLatency time.Duration `json:"max_latency"`

	// ErrorRate 错误率(0.0 - 1.0)
	ErrorRate float64 `json:"error_rate"`

	// Duration 实际运行时长
	Duration time.Duration `json:"duration"`

	// MemoryStart 起始内存使用(字节)
	MemoryStart uint64 `json:"memory_start"`

	// MemoryEnd 结束内存使用(字节)
	MemoryEnd uint64 `json:"memory_end"`

	// MemoryGrowth 内存增长(字节,可为负数)
	MemoryGrowth int64 `json:"memory_growth"`

	// GoroutineStart 起始 goroutine 数
	GoroutineStart int `json:"goroutine_start"`

	// GoroutineEnd 结束 goroutine 数
	GoroutineEnd int `json:"goroutine_end"`
}

StressResult 压力测试结果

包含性能指标、内存使用和 goroutine 信息。

func (*StressResult) String

func (r *StressResult) String() string

String 返回压力测试结果的可读字符串

type StressTest

type StressTest struct {
	// contains filtered or unexported fields
}

StressTest 压力测试

在高并发和持续负载下测试系统行为,支持以下特性:

  • 可配置并发数和持续时间
  • 升温阶段(ramp-up)逐步增加并发
  • 延迟统计(P50/P95/P99/Max)
  • 内存使用和 goroutine 泄漏检测
  • 错误率统计

使用示例:

st := NewStressTest("my_test", func(ctx context.Context) error {
    // 执行被测操作
    return nil
}, WithStressConcurrency(100), WithStressDuration(10*time.Second))
result, _ := st.Run(context.Background())
fmt.Println(result)

func NewStressTest

func NewStressTest(name string, fn func(ctx context.Context) error, opts ...StressOption) *StressTest

NewStressTest 创建压力测试

默认配置:10 并发、5 秒持续时间、无升温。

func (*StressTest) Run

func (s *StressTest) Run(ctx context.Context) (*StressResult, error)

Run 执行压力测试

创建指定数量的 goroutine,在持续时间内反复执行被测函数。 收集延迟数据并计算统计信息。 如果设置了升温时间,会逐步启动 goroutine。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL