swift-benchmark

一个 Swift 库,用于代码片段的基准测试,类似于 google/benchmark

示例

import Benchmark

benchmark("add string reserved capacity") {
    var x: String = ""
    x.reserveCapacity(2000)
    for _ in 1...1000 {
        x += "hi"
    }
}

Benchmark.main()

在运行时,您可以使用 --filter 命令行标志来过滤要运行的基准测试。有关可用选项的更多详细信息,请传递 -h--help 命令行标志。

示例

$ swift run -c release BenchmarkMinimalExample --help
USAGE: benchmark-command [--allow-debug-build] [--filter <filter>] [--filter-not <filter-not>] [--iterations <iterations>] [--warmup-iterations <warmup-iterations>] [--min-time <min-time>] [--max-iterations <max-iterations>] [--time-unit <time-unit>] [--inverse-time-unit <inverse-time-unit>] [--columns <columns>] [--format <format>] [--quiet]

OPTIONS:
  --allow-debug-build     Overrides check to verify optimized build.
  --filter <filter>       Run only benchmarks whose names match the regular expression.
  --filter-not <filter-not>
                          Exclude benchmarks whose names match the regular expression.
  --iterations <iterations>
                          Number of iterations to run.
  --warmup-iterations <warmup-iterations>
                          Number of warm-up iterations to run.
  --min-time <min-time>   Minimal time to run when automatically detecting number iterations.
  --max-iterations <max-iterations>
                          Maximum number of iterations to run when automatically detecting number iterations.
  --time-unit <time-unit> Time unit used to report the timing results.
  --inverse-time-unit <inverse-time-unit>
                          Inverse time unit used to report throughput results.
  --columns <columns>     Comma-separated list of column names to show.
  --format <format>       Output format (valid values are: json, csv, console, none).
  --quiet                 Only print final benchmark results.
  -h, --help              Show help information.

$ swift run -c release BenchmarkMinimalExample
running add string no capacity... done! (1832.52 ms)
running add string reserved capacity... done! (1813.96 ms)

name                         time     std        iterations
-----------------------------------------------------------
add string no capacity       37435 ns ±   6.22 %      37196
add string reserved capacity 37022 ns ±   1.75 %      37749

有关更多示例,请参阅 Sources/BenchmarkMinimalExampleSources/BenchmarkSuiteExample

用法

将此库添加为 SwiftPM 依赖项

let package = Package(
    name: ... ,
    products: [
        .executable(name: "Benchmarks", targets: ["Benchmarks"])
    ],
    dependencies: [
      .package(url: "https://github.com/google/swift-benchmark", from: "0.1.0")
    ],
    targets: [
        .target(
            name: "Benchmarks",
            dependencies: [.product(name: "Benchmark", package: "swift-benchmark")]
        )
    ]
)

路线图

该项目尚处于早期阶段,仅提供一套基本的基准测试实用程序。欢迎提交 issue 和功能请求,以帮助我们确定下一步工作的优先级。

许可

详情请参阅 LICENSE

贡献

详情请参阅 CONTRIBUTING.md