> [!NOTE] > 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。 > [English](./README.en.md) · [原始项目](https://github.com/google/benchmark) · [上游 README](https://github.com/google/benchmark/blob/HEAD/README.md) > 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。 # Benchmark [![build-and-test](https://github.com/google/benchmark/workflows/build-and-test/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Abuild-and-test) [![bazel](https://github.com/google/benchmark/actions/workflows/bazel.yml/badge.svg)](https://github.com/google/benchmark/actions/workflows/bazel.yml) [![test-bindings](https://github.com/google/benchmark/workflows/test-bindings/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Atest-bindings) [![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark) [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/benchmark/badge)](https://securityscorecards.dev/viewer/?uri=github.com/google/benchmark) [![Discord](https://discordapp.com/api/guilds/1125694995928719494/widget.png?style=shield)](https://discord.gg/cz7UX7wKC2) 用于对代码片段进行基准测试(benchmark)的库,类似于单元测试。示例: ```c++ #include #include static void BM_SomeFunction(benchmark::State& state) { // Perform setup here for (auto _ : state) { // This code gets timed SomeFunction(); } } // Register the function as a benchmark BENCHMARK(BM_SomeFunction); // Run the benchmark BENCHMARK_MAIN(); ``` ## 入门 要开始使用,请参阅[环境要求](#requirements)和 [安装](#installation)。完整示例见[用法](#usage),更全面的功能概览见 [用户指南](docs/user_guide.md)。 阅读 [Google Test 文档](https://github.com/google/googletest/blob/main/docs/primer.md) 也可能有所帮助,因为 API 在结构上的某些方面较为相似。 ## 资源 [讨论组](https://groups.google.com/d/forum/benchmark-discuss) IRC 频道: * [libera](https://libera.chat) #benchmark [附加工具文档](docs/tools.md) [汇编测试文档](docs/AssemblyTests.md) [构建并安装 Python 绑定](docs/python_bindings.md) ## 环境要求 该库可在 C++11 下使用。不过,构建时需要 C++17,包括编译器和标准库支持。 _有关支持的编译器和标准的更多详情,请参阅 [dependencies.md](docs/dependencies.md)。_ 如果你需要支持特定编译器,非常欢迎提交补丁。 请参阅[平台特定构建说明](docs/platform_specific_build_instructions.md)。 ## 安装 本节介绍使用 cmake 的安装流程。作为前提条件,你需要安装 git 和 cmake。 _有关支持的构建工具版本的更多详情,请参阅 [dependencies.md](docs/dependencies.md)。_ ```bash # Check out the library. $ git clone https://github.com/google/benchmark.git # Go to the library root directory $ cd benchmark # Make a build directory to place the build output. $ cmake -E make_directory "build" # Generate build system files with cmake, and download any dependencies. $ cmake -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on -DCMAKE_BUILD_TYPE=Release -S . -B "build" # Build the library. $ cmake --build "build" --config Release ``` 这会构建 `benchmark` 和 `benchmark_main` 库及测试。 在 Unix 系统上,构建目录现在应大致如下: ``` /benchmark /build /src /libbenchmark.a /libbenchmark_main.a /test ... ``` 接下来,你可以运行测试以检查构建结果。 ```bash $ cmake -E chdir "build" ctest --build-config Release ``` 如果你希望全局安装该库,还需运行: ``` sudo cmake --build "build" --config Release --target install ``` 请注意,Google Benchmark 需要 Google Test 来构建和运行测试。可通过以下两种方式提供该依赖: * 将 Google Test 源码检出到 `benchmark/googletest`。 * 否则,若在配置时如上指定 `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON`, 库会自动下载并构建任何所需的依赖。 如果你不想构建和运行测试,请将 `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF` 添加到 `CMAKE_ARGS`。 ### Debug 与 Release 默认情况下,benchmark 会作为 debug 库构建。出现这种情况时,输出中会出现警告。若要改为构建 release 库,请在生成构建系统文件时添加 `-DCMAKE_BUILD_TYPE=Release`,如上所示。在构建命令中使用 `--config Release` 是为了正确支持多配置工具(例如 Visual Studio),对于其他构建系统(如 Makefile)可以省略。 要启用链接时优化(link-time optimisation),在生成构建系统文件时还需添加 `-DBENCHMARK_ENABLE_LTO=true`。 如果你使用 gcc,若自动检测失败,可能需要设置 `GCC_AR` 和 `GCC_RANLIB` cmake 缓存变量。 如果你使用 clang,可能需要设置 `LLVMAR_EXECUTABLE`、 `LLVMNM_EXECUTABLE` 和 `LLVMRANLIB_EXECUTABLE` cmake 缓存变量。 要启用 sanitizer 检查(例如 `asan` 和 `tsan`),请添加: ``` -DCMAKE_C_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all" -DCMAKE_CXX_FLAGS="-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all " ``` ### 稳定版与实验版 main 分支包含基准测试库的最新稳定版本; 其 API 可认为大体稳定,仅在发布新的主版本时才会引入破坏源代码兼容性的变更。 较新的实验性功能在 [`v2` 分支](https://github.com/google/benchmark/tree/v2). 上实现和测试。欢迎希望使用、测试新功能并提供反馈的用户尝试该分支。不过,该分支不提供稳定性保证,并保留随时更改和破坏 API 的权利。 ## 用法 ### 基本用法 定义一个执行待测量代码的函数,使用 `BENCHMARK` 宏将其注册为基准测试函数,并确保提供了合适的 `main` 函数: ```c++ #include static void BM_StringCreation(benchmark::State& state) { for (auto _ : state) std::string empty_string; } // Register the function as a benchmark BENCHMARK(BM_StringCreation); // Define another benchmark static void BM_StringCopy(benchmark::State& state) { std::string x = "hello"; for (auto _ : state) std::string copy(x); } BENCHMARK(BM_StringCopy); BENCHMARK_MAIN(); ``` 要运行基准测试,请编译并链接 `benchmark` 库 (libbenchmark.a/.so)。如果你按照上述构建步骤操作,该库将位于你创建的构建目录下。 ```bash # Example on linux after running the build steps above. Assumes the # `benchmark` and `build` directories are under the current directory. $ g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \ -Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark ``` 或者,链接 `benchmark_main` 库并移除 上文中的 `BENCHMARK_MAIN();`,以获得相同行为。 编译后的可执行文件默认会运行所有基准测试。传入 `--help` 标志可查看选项信息,或参阅[用户指南](docs/user_guide.md)。 ### 在 CMake 中使用 如果使用 CMake,建议使用 `target_link_libraries` 链接项目提供的 `benchmark::benchmark` 或 `benchmark::benchmark_main` 目标。 当你的目标定义了自己的 `main` 函数时,链接 `benchmark::benchmark`;若要使用默认的基准测试入口点,则链接 `benchmark::benchmark_main`。`benchmark::benchmark_main` 目标会传递链接 `benchmark::benchmark`。 可以使用 ```find_package``` 导入已安装的库版本。 ```cmake find_package(benchmark REQUIRED) ``` 或者,```add_subdirectory``` 会将库直接纳入你的 CMake 项目中。 ```cmake add_subdirectory(benchmark) ``` 无论哪种方式,都按如下方式链接该库。 ```cmake target_link_libraries(MyTarget benchmark::benchmark) # Or, when you do not define your own main: target_link_libraries(MyTarget benchmark::benchmark_main) ``` 当基准测试源文件通过中间 CMake 目标共享时,应选择对象库(object library)而非静态库: ```cmake add_library(shared_benchmarks OBJECT bench.cc) target_link_libraries(shared_benchmarks benchmark::benchmark_main) add_executable(runnable_benchmarks) target_link_libraries(runnable_benchmarks shared_benchmarks) ``` 这会链接包含 `BENCHMARK` 注册的对象文件到最终可执行文件中。如果这些注册仅放在中间的 `STATIC` 库中,链接器可能不会复制静态注册符号,因此基准测试不会成为最终可执行文件的一部分。 #### 在另一个 CMake 项目中嵌入 Google Benchmark 从 CMake 项目使用 Google Benchmark 有两种常见方式: * 使用已安装或由包管理器维护的副本,例如来自系统包管理器或 vcpkg,并通过 `find_package(benchmark REQUIRED)` 导入。 * 将此仓库添加到源码树中,例如作为子模块或 `FetchContent` 依赖,并调用 `add_subdirectory`。 已安装形式将 Google Benchmark 的构建与父项目分离,对于系统包和 vcpkg 通常是最简单的选择。源码树形式在父项目需要固定特定提交或将 Google Benchmark 作为其正常 CMake 配置步骤的一部分进行构建时很有用。 从源码嵌入时,大多数项目应关闭 Google Benchmark 的测试和安装规则: ```cmake set(BENCHMARK_ENABLE_GTEST_TESTS OFF CACHE BOOL "" FORCE) set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE) set(BENCHMARK_ENABLE_INSTALL OFF CACHE BOOL "" FORCE) add_subdirectory(third_party/benchmark) target_link_libraries(MyTarget benchmark::benchmark) ``` 如果父级构建尚未提供 Google Test,可以在 `benchmark/googletest` 下检出 Google Test 源码,或使用 `BENCHMARK_DOWNLOAD_DEPENDENCIES=ON` 进行配置。对于仅链接 benchmark 库而不构建 Google Benchmark 测试的项目,禁用 `BENCHMARK_ENABLE_GTEST_TESTS` 可避免 Google Test 依赖。 Google Benchmark 在选择静态或共享库输出时遵循 CMake 的 `BUILD_SHARED_LIBS` 设置。在 Windows 上,请保持此设置与项目的其余部分一致,并确保 benchmark 库和链接它的目标使用相同的运行时库配置。 ### 与 Bazel 一起使用 如果使用带 Bzlmod 的 Bazel,请将 Google Benchmark 添加到 `MODULE.bazel` 文件中: ```starlark bazel_dep(name = "google_benchmark", version = "") ``` 将 `` 替换为你想使用的 Google Benchmark 发布版本。 然后将 `cc_binary` 或 `cc_test` 链接到提供的某个目标之一: ```starlark load("@rules_cc//cc:defs.bzl", "cc_binary") cc_binary( name = "my_benchmark", srcs = ["my_benchmark.cc"], deps = ["@google_benchmark//:benchmark_main"], ) ``` 当你的目标定义自己的 `main` 函数时(包括通过 `BENCHMARK_MAIN()`),使用 `@google_benchmark//:benchmark`。使用 `@google_benchmark//:benchmark_main` 可使用默认的 Google Benchmark 入口点。 有关 WORKSPACE 设置及更多示例,请参阅 [Bazel](docs/bazel.md)。