Skip to content

基准测试

一句话解释

基准测试测量特定代码运行速度——每秒操作数、执行时间——用于比较实现。

用大白话说

基准测试测量特定代码或操作的性能。与性能测试(测试用户体验)不同,基准测试关注代码级性能用于比较和优化。基准测量什么:1. 每秒操作数——函数每秒能执行多少次

  1. 执行时间——特定操作耗时(纳秒/微秒)
  2. 内存使用——操作分配多少内存
  3. 比较性能——算法 A vs 算法 B

用例:1. 比较实现——新算法比旧算法快吗?2. 跟踪退化——这次变更让东西变慢了吗?3. 找瓶颈——哪个函数最慢?4. 验证优化——优化真的有帮助吗?注意:基准测试可能有误导。始终:

  • 运行多次迭代取平均/中位数
  • 测量前预热 JIT/编译器
  • 隔离系统噪声(其他进程、I/O)
  • 使用统计分析(不只一次运行)

工具:Benchmark.js(JS)、pytest-benchmark(Python)、JMH(Java)、criterion(Rust)。

示例

javascript
// Benchmark.js — compare two sorting implementations
import Benchmark from 'benchmark';

const suite = new Benchmark.Suite();

const data = Array.from({ length: 10000 }, () => Math.random());

suite
  .add('Array.sort() (built-in)', () => {
    const arr = [...data];
    arr.sort((a, b) => a - b);
  })
  .add('bubble sort (custom)', () => {
    const arr = [...data];
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr.length - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
          [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        }
      }
    }
  })
  .on('complete', function () {
    console.log('Fastest is ' + this.filter('fastest').map('name'));
    // Output: Fastest is Array.sort() (built-in)
    // Array.sort(): 2.31 ops/sec
    // bubble sort: 0.02 ops/sec (100x slower!)
  })
  .run();

Benchmark.js 多次运行每个函数并报告 ops/sec。内置排序比冒泡排序快 100 倍——基准测试为优化决策提供硬数据。

常见混淆

  • 容易混淆的对象: performance testing

    关键区别: 基准测试在代码级测量特定代码/算法性能——函数执行时间、ops/sec。性能测试测量用户面向性能——页面加载时间、API 延迟。基准测试给开发者比较代码;性能测试确保良好用户体验。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表