# @fluid-tools/benchmark 中文文档

规范地址：https://npmcn.com/package/%40fluid-tools/benchmark/

版本：0\.59\.0
npm 元数据更新时间：2026-07-29T21:10:38.594Z
中文译文更新时间：2026-11-15T02:29:33.945Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fluid-tools/benchmark
原文对照：https://npmcn.com/package/%40fluid-tools/benchmark/?lang=original
项目主页：https://fluidframework.com/
源码仓库：https://github.com/microsoft/FluidFramework

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：527 kB，122 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：3 个
- 首次发布：2021-06-21T19:33:25.982Z
- 最新版本发布：2026-04-29T19:59:49.416Z
- 近 30 天下载量：4529（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：32（近 12 个月 14 个）

## 中文简介

基准工具

## 安装

```sh
npm install @fluid-tools/benchmark
```

也可以使用：`pnpm add @fluid-tools/benchmark`、`yarn add @fluid-tools/benchmark`、`bun add @fluid-tools/benchmark`

## README

# @ fluid-tools/ 基准

这个软件包包含用于描述运行时间和内存使用的基准工具. 它提供您需要的工具来配置您自己的代码( 下面描述) 和各种用于自定义和配置的工具 基准,以及编写替代记者和剖析功能(例如,支持测试框架,而不是 摩诃迦叶.

## 一般用途

此套件导出 `benchmarkIt` 用来代替摩卡的 `it()` 以定义基准测试.

使用 `benchmarkIt` 双倍为正确性测试:无 `--perfMode` 他们的行为就像其他摩卡人 `it()` 测试.

作为基准测试,请引用 `mocha` 照你平时对你的包裹的用意 但通过一些额外的论据, 像这样:

```console
--v8-expose-gc --perfMode --fgrep @Benchmark --reporter @fluid-tools/benchmark/dist/mocha/Reporter.js
```

### `--perfMode` (必须)

启用性能测试模式而不是正确性测试模式. 在性能测试模式下,每次测试都会运行并测量出许多迭代. 在正确测试模式中,只运行一个迭代,没有进行测量.

也可以使用 `FLUID_TEST_PERF_MODE` 环境变量. 如果使用 [Mocha 并行模式](https://mochajs.org/features/parallel-mode/), (中文(简体) ), 然后必须使用环境变量来设定.

### `--v8-expose-gc` (必须)

这是必要的,这样包就可以在测试之间进行明确的垃圾收集,以帮助减少 交叉测试污染并获得内存测试的准确结果.

### `--fgrep @Benchmark`

使用此包中的工具创建的所有测试都标记为 `@Benchmark`,因此使用 `--fgrep @Benchmark` 只运行 基准测试. 每个测试也根据其 `type` 选项 : `@Measurement` (默认), `@Perspective`,或 `@Diagnostic`。 。 。 . 使用更具体的过滤器 `--fgrep @Measurement` 仅进行特定类型的测试.

请注意,Mocha只支持一个 `fgrep` 或者说 `grep` 一次辩论,所以如果你有其他过滤器, 可能需要合并成一个更复杂的 `--grep` 选项.

### `--reporter <path>`

让您指定自定义报告员输出测试结果的路径 . 此软件包包括 `dist/mocha/Reporter.js`。 。 。 . 如果你不指定一个,默认的摩卡记者将接手,你看不到基准信息.

### `--reporterOptions reportFile=<output-path>`

如果您使用此软件包中的记者, 您可以为此设置输出文件路径 . 所有基准结果采用分级法合并成一个 JSON 文件 `ReportArray` 结构. 如果省略,则不撰写文件(结果仍然被打印到控制台上).

### `--parentProcess`

如果你通过这个 **选项** 当每个性能测试都处于一个分叉儿童过程中时. 叉线程序只进行测试,并将结果传播给父母. 这可带来很大的间接费用(儿童过程会重新进行Mocha测试发现,这可能会引起很大的启动费用, 除了fakeing Node.js的间接费用之外,但降低了以前测试对状态的影响 jIT和堆积. 在你的情景中彻底测试一下 以确保权衡是值得的.

使用 `--parentProcess` 当前不支持 [Mocha 并行模式](https://mochajs.org/features/parallel-mode/)。 。 。 .

## 剖析时间

用于描述运行时间长度, 使用 `benchmarkIt` 合并 `benchmarkDuration`数字 :

```typescript
benchmarkIt({
    title: "My sync test",
    ...benchmarkDuration({
        benchmarkFn: () => {
            // synchronous code to benchmark
        },
    }),
});

benchmarkIt({
    title: "My async test",
    ...benchmarkDuration({
        benchmarkFnAsync: async () => {
            // asynchronous code to benchmark
        },
    }),
});
```

`benchmarkDuration` 接受一个 `DurationBenchmark`,它必须具有:

-   `benchmarkFn` ——用于基准的同步函数.
-   `benchmarkFnAsync` ——用于基准的同步函数.
-   `benchmarkFnCustom` ——通过 a 直接管理分批循环的同位素函数 `BenchmarkTimer` 参数, 对于需要完全控制时间的情况。 使用 `state.timeBatch(fn)` - 普通案件,或 `state.timer.now()` 编号 : `state.recordBatch()` 当您需要从测量时间中排除设置/关闭时.

也可以选择 `BenchmarkTimingOptions` 调奏 `maxBenchmarkDurationSeconds`, (中文(简体) ), `minBatchCount`,以及 `minBatchDurationSeconds`。 。 。 .

见文档 `DurationBenchmark` 财务报告和审定财务报表 `BenchmarkTimingOptions` 更多细节.

> **页:1**:在设定不纯函数基准时要注意陷阱. 测试执行策略假设 `benchmarkFn` 是一个独立事件. 用于全面控制每个批次的设置和拆卸,使用 `benchmarkFnCustom`。 。 。 . 见 `DurationBenchmarkCustom` 详细情况.

## 剖析自定义测量

要报告完全定制的测量, 呼叫 `benchmarkIt` 直接提供 `run` 函数返回 a `CollectedData`数字 :

```typescript
benchmarkIt({
    title: "My custom measurement",
    run: (): CollectedData => [
        {
            // The first element is the primary measurement (all fields required).
            name: "My metric",
            value: 42,
            units: "things/op",
            type: ValueType.SmallerIsBetter,
            significance: "Primary",
        },
        // Additional measurements are optional.
        {
            name: "Sample count",
            value: 100,
            units: "count",
        },
    ],
});
```

`CollectedData` 是个大便 `[PrimaryMeasurement, ...Measurement[]]`第一个要素是主要计量(用于回归检测),需要所有字段: `name`, (中文(简体) ), `value`, (中文(简体) ), `units`, (中文(简体) ), `type`,以及 `significance: "Primary"`. 其他测量是可选的 `units`, (中文(简体) ), `type`,以及 `significance` 字段也是可选的.

`collectDurationData` 财务报告和审定财务报表 `collectMemoryUseData` 可直接在 `run` 函数,比 `benchmarkDuration` 或者说 `benchmarkMemoryUse` 当您需要在定时区域外添加自定义测量或运行设置/设置时:

```typescript
benchmarkIt({
    title: "My custom duration measurement",
    run: async (): Promise<CollectedData> => {
        // Optional setup can run here
        const data = await collectDurationData({
            benchmarkFn: () => {
                // code to benchmark
            },
        });
        // Extra measurements can be added:
        return [...data, { name: "Extra metric", value: 1 }];
    },
});
```

## 描述内存使用情况

配置内存使用、使用 `benchmarkIt` 合并 `benchmarkMemoryUse`数字 :

```typescript
benchmarkIt({
    title: "My memory test",
    ...benchmarkMemoryUse({
        benchmarkFn: async (state) => {
            // If your test requires one-time setup, do it here:
            const holder: { value: unknown } = { value: undefined };
            while (state.continue()) {
                // Release the previous allocation, then do any per-iteration setup.
                holder.value = undefined;
                // Collect a baseline "before" heap measurement.
                await state.beforeAllocation();
                // Allocate the memory you want to measure.
                holder.value = createSomething();
                // Collect an "after allocation" heap measurement.
                await state.whileAllocated();
                // To help confirm you are measuring the allocation you expect,
                // you can optionally free it here then call afterDeallocation:
                // holder.value = undefined;
                // await state.afterDeallocation();
            }
        },
    }),
});
```

这衡量了堆积中保留部分与 `beforeAllocation` 改为 `whileAllocated`。 。 。 . 这不包括操作中曾经使用但在操作前释放的内存 `whileAllocated` 被调用.

论点 `benchmarkMemoryUse` 必须执行 `MemoryUseBenchmark`,则需要 `benchmarkFn` 属性. 该函数收到一个 `MemoryUseCallbacks` 对象并必须循环到 `state.continue()` 返回虚假, 随行 此模式每个迭代 :

1.  发布先前迭代中分配的任何内存的引用(因此GC可以再取).
2.  设置在测试下进行分配所需的任何内容,不应包括在测量中.
3.  `state.beforeAllocation()` ——GC运行并进行基线"前"堆积测量.
4.  执行您想要测量的内存分配操作 .
5.  `state.whileAllocated()` ——GC运行并进行"分配后"堆积测量.
6.  _(备选)_ 免费记忆,然后呼叫 `state.afterDeallocation()` ——如果被调用,GC运行,并进行"交易后"堆积测量.

基准报告“分配时间”和“之前”在重复读取之间的平均比值. 内存不得在迭代中积累(即您在第四步中分配的东西必须完全可回放).

详情见文件编号: `MemoryUseBenchmark` 财务报告和审定财务报表 `MemoryUseCallbacks`。 。 。 .

## 贡献准则

有多种办法 [贡献](https://github.com/microsoft/FluidFramework/blob/main/CONTRIBUTING.md) 给流体.

-   参加我们的"A" [GitHub 讨论](https://github.com/microsoft/FluidFramework/discussions)。 。 。 .
-   [提交错误](https://github.com/microsoft/FluidFramework/issues) 并且帮助我们核实 纠正他们被检查.
-   评议 [源代码更改](https://github.com/microsoft/FluidFramework/pulls)。 。 。 .
-   [贡献错误修正](https://github.com/microsoft/FluidFramework/blob/main/CONTRIBUTING.md)。 。 。 .

可在 [维基](https://github.com/microsoft/FluidFramework/wiki)。 。 。 .

该项目通过了 [Microsoft 开源行为守则](https://opensource.microsoft.com/codeofconduct/)。 。 。 . 更多信息见 [《行为守则》](https://opensource.microsoft.com/codeofconduct/faq/) 或联系人 [打开码@ microsoft.com](mailto:opencode@microsoft.com) 并附上任何其他问题或评论.

这个项目可能包含微软项目的商标或标志,产品,或服务. 这些商标或标志的使用必须遵循微软 [商标和品牌准则](https://www.microsoft.com/trademarks)。 。 。 . 在这个项目的修改后版本中使用微软商标或标志不得造成混淆或暗示微软赞助.

## 帮助

找不到你在读什么? 检查出来 [(原始内容存档于2018-10-21) (中文(简体) ). slidframework.com](https://fluidframework.com/docs/)。 。 。 .

还是找不到你要找的东西? 请 [提交问题](https://github.com/microsoft/FluidFramework/wiki/Submitting-Bugs-and-Feature-Requests)。 。 。 .

谢谢!

## 商标

这个项目可能包含微软项目的商标或标志,产品,或服务.

这些商标或标志的使用必须遵循微软的 [商标和品牌准则](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general)。 。 。 .

在这个项目的修改后版本中使用微软商标或标志不得造成混淆或暗示微软赞助.

## 常见问题

### @fluid-tools/benchmark 是什么？

基准工具

### 如何安装 @fluid-tools/benchmark？

在项目目录运行 npm install @fluid-tools/benchmark，或使用 pnpm add / yarn add / bun add。

### @fluid-tools/benchmark 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fluid-tools/benchmark 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fluid-tools/benchmark 可以商用吗？

@fluid-tools/benchmark 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fluid-tools/benchmark 的下载量有多少？

根据 npm 官方下载统计，@fluid-tools/benchmark 在 2026/10/15 – 2026/11/13 这 30 天内被下载 4,529 次，日均约 151 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fluid-tools/benchmark 还在维护吗？

最新版本 0\.59\.0 发布于 2026/04/30（6 个月前）；至今共发布 32 个版本，其中过去 12 个月发布了 14 个；首次发布于 2021/06/22。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

