Debian 12与13系统性能暴力测试代码

我们需要用于对 Debian 12 和 13 系统进行暴力性能测试并生成测试结果报告。这个方法结合了多种性能测试工具和方法,包括 CPU、内存、I/O 和网络等方面的测试。

方案概述

  1. 测试环境准备:安装必要的工具和依赖

  2. 测试内容设计

    • CPU 密集型任务测试

    • 内存操作性能测试

    • 磁盘 I/O 性能测试

    • 网络性能测试

    • 系统综合负载测试

  3. 测试结果收集与分析:生成详细的测试报告

完整代码实现

const fs = require('fs');
const path = require('path');
const { performance, PerformanceObserver } = require('perf_hooks');
const { execSync } = require('child_process');
const os = require('os');
const axios = require('axios');
const Benchmark = require('benchmark');
const autocannon = require('autocannon');
const faker = require('faker');

// 测试结果存储
const testResults = {
  systemInfo: {},
  cpuTests: [],
  memoryTests: [],
  diskTests: [],
  networkTests: [],
  loadTests: [],
  summary: {}
};

// 1. 获取系统信息
function collectSystemInfo() {
  testResults.systemInfo = {
    os: os.type(),
    platform: os.platform(),
    arch: os.arch(),
    release: os.release(),
    hostname: os.hostname(),
    totalMem: os.totalmem(),
    freeMem: os.freemem(),
    cpus: os.cpus(),
    loadavg: os.loadavg(),
    uptime: os.uptime(),
    debianVersion: getDebianVersion()
  };
}

function getDebianVersion() {
  try {
    const osRelease = fs.readFileSync('/etc/os-release', 'utf8');
    const versionMatch = osRelease.match(/VERSION_ID="([^"]+)"/);
    return versionMatch ? versionMatch[1] : 'unknown';
  } catch (e) {
    return 'unknown';
  }
}

// 2. CPU性能测试
function runCpuTests() {
  console.log('开始CPU性能测试...');
  
  // 测试1: 计算密集型任务 - 素数计算
  const primeTest = () => {
    const start = performance.now();
    let primes = [];
    for (let i = 0; i < 50000; i++) {
      if (isPrime(i)) primes.push(i);
    }
    const end = performance.now();
    return end - start;
  };
  
  const isPrime = num => {
    for(let i = 2; i < num; i++)
      if(num % i === 0) return false;
    return num > 1;
  };
  
  // 测试2: 浮点运算
  const floatTest = () => {
    const start = performance.now();
    let result = 0;
    for (let i = 0; i < 10000000; i++) {
      result += Math.sqrt(i) * Math.sin(i);
    }
    const end = performance.now();
    return end - start;
  };
  
  // 测试3: 使用Benchmark.js进行基准测试
  const benchmarkTest = new Promise(resolve => {
    const suite = new Benchmark.Suite;
    suite.add('RegExp#test', () => /o/.test('Hello World!'))
      .add('String#indexOf', () => 'Hello World!'.indexOf('o') > -1)
      .on('cycle', event => {
        testResults.cpuTests.push({
          name: event.target.name,
          hz: event.target.hz,
          stats: event.target.stats
        });
      })
      .on('complete', function() {
        resolve();
      })
      .run({ 'async': true });
  });
  
  // 运行测试
  testResults.cpuTests.push({
    name: '素数计算(0-50000)',
    time: primeTest(),
    unit: 'ms'
  });
  
  testResults.cpuTests.push({
    name: '浮点运算(1000万次)',
    time: floatTest(),
    unit: 'ms'
  });
  
  return benchmarkTest;
}

// 3. 内存性能测试
function runMemoryTests() {
  console.log('开始内存性能测试...');
  
  // 测试1: 内存分配与释放
  const allocTest = () => {
    const start = performance.now();
    const arr = [];
    for (let i = 0; i < 1000000; i++) {
      arr.push(faker.datatype.uuid());
    }
    const end = performance.now();
    return {
      time: end - start,
      memoryUsage: process.memoryUsage()
    };
  };
  
  // 测试2: 内存复制速度
  const copyTest = () => {
    const largeArray = new Array(1000000).fill(null).map(() => faker.datatype.uuid());
    const start = performance.now();
    const copyArray = [...largeArray];
    const end = performance.now();
    return end - start;
  };
  
  // 测试3: 内存泄漏检测
  const leakTest = () => {
    const startMem = process.memoryUsage().heapUsed;
    const leaks = [];
    
    for (let i = 0; i < 10000; i++) {
      leaks.push(new Array(100).fill(faker.datatype.uuid()));
    }
    
    const endMem = process.memoryUsage().heapUsed;
    return endMem - startMem;
  };
  
  // 运行测试
  const allocResult = allocTest();
  testResults.memoryTests.push({
    name: '内存分配(100万UUID)',
    time: allocResult.time,
    memoryUsage: allocResult.memoryUsage,
    unit: 'ms'
  });
  
  testResults.memoryTests.push({
    name: '内存复制(100万元素数组)',
    time: copyTest(),
    unit: 'ms'
  });
  
  testResults.memoryTests.push({
    name: '内存泄漏测试',
    leakedBytes: leakTest(),
    unit: 'bytes'
  });
}

// 4. 磁盘I/O性能测试
function runDiskTests() {
  console.log('开始磁盘I/O性能测试...');
  
  // 测试1: 顺序写入速度
  const writeTest = () => {
    const filePath = path.join(__dirname, 'temp_write_test.dat');
    const start = performance.now();
    const stream = fs.createWriteStream(filePath);
    
    return new Promise(resolve => {
      for (let i = 0; i < 100000; i++) {
        stream.write(faker.lorem.paragraph() + '\n');
      }
      
      stream.end(() => {
        const end = performance.now();
        fs.unlinkSync(filePath);
        resolve(end - start);
      });
    });
  };
  
  // 测试2: 顺序读取速度
  const readTest = () => {
    const filePath = path.join(__dirname, 'temp_read_test.dat');
    // 先创建测试文件
    const data = new Array(10000).fill(null).map(() => faker.lorem.paragraph()).join('\n');
    fs.writeFileSync(filePath, data);
    
    const start = performance.now();
    const content = fs.readFileSync(filePath, 'utf8');
    const end = performance.now();
    
    fs.unlinkSync(filePath);
    return end - start;
  };
  
  // 测试3: 使用系统工具测试磁盘性能
  const sysDiskTest = () => {
    try {
      const result = execSync('dd if=/dev/zero of=/tmp/test bs=1M count=1024 conv=fdatasync 2>&1');
      const output = result.toString();
      const speedMatch = output.match(/(\d+\.\d+) MB\/s/);
      return speedMatch ? parseFloat(speedMatch[1](@ref) : null;
    } catch (e) {
      console.error('系统磁盘测试失败:', e.message);
      return null;
    }
  };
  
  // 运行测试
  return Promise.all([writeTest(), readTest()])
    .then(([writeTime, readTime]) => {
      testResults.diskTests.push({
        name: '顺序写入(10万段落)',
        time: writeTime,
        unit: 'ms'
      });
      
      testResults.diskTests.push({
        name: '顺序读取(1万段落)',
        time: readTime,
        unit: 'ms'
      });
      
      const diskSpeed = sysDiskTest();
      if (diskSpeed) {
        testResults.diskTests.push({
          name: '磁盘写入速度(dd命令)',
          speed: diskSpeed,
          unit: 'MB/s'
        });
      }
    });
}

// 5. 网络性能测试
function runNetworkTests() {
  console.log('开始网络性能测试...');
  
  // 测试1: 本地HTTP服务器性能
  const httpServerTest = () => {
    return new Promise(resolve => {
      const server = require('http').createServer((req, res) => {
        res.end('OK');
      });
      
      server.listen(0, () => {
        const port = server.address().port;
        const url = ` http://localhost:$ {port}`;
        
        autocannon({
          url: url,
          connections: 100,
          duration: 10,
          title: '本地HTTP服务器测试'
        }, (err, result) => {
          server.close();
          if (err) {
            console.error('HTTP服务器测试失败:', err);
            resolve(null);
          } else {
            resolve(result);
          }
        });
      });
    });
  };
  
  // 测试2: 外部网络请求延迟
  const externalLatencyTest = () => {
    const testUrls = [
      ' https://www.google.com',
      ' https://www.github.com',
      ' https://www.debian.org'
    ];
    
    return Promise.all(testUrls.map(url => {
      const start = performance.now();
      return axios.head(url)
        .then(() => {
          const end = performance.now();
          return {
            url: url,
            latency: end - start
          };
        })
        .catch(() => ({
          url: url,
          latency: null,
          error: true
        }));
    }));
  };
  
  // 运行测试
  return Promise.all([httpServerTest(), externalLatencyTest()])
    .then(([httpResult, latencyResults]) => {
      if (httpResult) {
        testResults.networkTests.push({
          name: '本地HTTP服务器性能',
          requests: httpResult.requests.total,
          duration: httpResult.duration,
          latency: httpResult.latency,
          throughput: httpResult.throughput,
          unit: {
            requests: 'requests',
            duration: 's',
            latency: 'ms',
            throughput: 'req/s'
          }
        });
      }
      
      latencyResults.forEach(result => {
        if (!result.error) {
          testResults.networkTests.push({
            name: `外部网络延迟 - ${result.url}`,
            latency: result.latency,
            unit: 'ms'
          });
        }
      });
    });
}

// 6. 系统综合负载测试
function runLoadTests() {
  console.log('开始系统综合负载测试...');
  
  // 测试1: 使用stress-ng工具进行系统压力测试
  const stressTest = () => {
    try {
      // 安装stress-ng (如果未安装)
      try {
        execSync('which stress-ng || sudo apt install -y stress-ng', { stdio: 'pipe' });
      } catch (e) {
        console.error('无法安装stress-ng:', e.message);
        return null;
      }
      
      // 运行CPU、内存、I/O综合测试60秒
      const start = performance.now();
      execSync('stress-ng --cpu 4 --vm 2 --vm-bytes 1G --io 2 --timeout 60s --metrics-brief', { stdio: 'pipe' });
      const end = performance.now();
      
      return end - start;
    } catch (e) {
      console.error('stress-ng测试失败:', e.message);
      return null;
    }
  };
  
  // 测试2: 使用wrk进行高并发HTTP测试
  const wrkTest = () => {
    try {
      // 安装wrk (如果未安装)
      try {
        execSync('which wrk || sudo apt install -y wrk', { stdio: 'pipe' });
      } catch (e) {
        console.error('无法安装wrk:', e.message);
        return null;
      }
      
      // 启动测试HTTP服务器
      const server = require('http').createServer((req, res) => {
        res.end('OK');
      });
      
      return new Promise(resolve => {
        server.listen(0, () => {
          const port = server.address().port;
          const result = execSync(`wrk -t12 -c400 -d30s http://localhost:$ {port}`, { stdio: 'pipe' }).toString();
          server.close();
          
          const matches = result.match(/Requests\/sec:\s+(\d+\.\d+)/);
          const rps = matches ? parseFloat(matches[1](@ref) : null;
          
          resolve(rps);
        });
      });
    } catch (e) {
      console.error('wrk测试失败:', e.message);
      return null;
    }
  };
  
  // 运行测试
  return Promise.all([stressTest(), wrkTest()])
    .then(([stressTime, wrkRps]) => {
      if (stressTime) {
        testResults.loadTests.push({
          name: 'stress-ng综合负载测试',
          duration: stressTime,
          unit: 'ms'
        });
      }
      
      if (wrkRps) {
        testResults.loadTests.push({
          name: 'wrk高并发HTTP测试',
          requestsPerSecond: wrkRps,
          unit: 'req/s'
        });
      }
    });
}

// 生成测试报告
function generateReport() {
  console.log('生成测试报告...');
  
  // 计算各项测试的平均值
  const calculateAverage = (tests, key) => {
    const values = tests.map(t => t[key]).filter(v => typeof v === 'number');
    return values.length ? values.reduce((a, b) => a + b, 0) / values.length : null;
  };
  
  testResults.summary = {
    cpu: {
      averageTime: calculateAverage(testResults.cpuTests, 'time'),
      averageHz: calculateAverage(testResults.cpuTests.filter(t => t.hz), 'hz')
    },
    memory: {
      averageTime: calculateAverage(testResults.memoryTests.filter(t => t.time), 'time'),
      averageLeak: calculateAverage(testResults.memoryTests.filter(t => t.leakedBytes), 'leakedBytes')
    },
    disk: {
      averageTime: calculateAverage(testResults.diskTests.filter(t => t.time), 'time'),
      averageSpeed: calculateAverage(testResults.diskTests.filter(t => t.speed), 'speed')
    },
    network: {
      averageLatency: calculateAverage(testResults.networkTests.filter(t => t.latency), 'latency'),
      averageThroughput: calculateAverage(testResults.networkTests.filter(t => t.throughput), 'throughput')
    },
    load: {
      averageRPS: calculateAverage(testResults.loadTests.filter(t => t.requestsPerSecond), 'requestsPerSecond')
    }
  };
  
  // 保存报告到文件
  const reportDir = path.join(__dirname, 'reports');
  if (!fs.existsSync(reportDir)) {
    fs.mkdirSync(reportDir);
  }
  
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
  const reportFile = path.join(reportDir, `performance-report-${timestamp}.json`);
  
  fs.writeFileSync(reportFile, JSON.stringify(testResults, null, 2));
  console.log(`测试报告已保存到: ${reportFile}`);
  
  // 同时生成HTML报告
  generateHtmlReport(reportFile);
}

function generateHtmlReport(jsonFile) {
  const htmlReportFile = jsonFile.replace('.json', '.html');
  const jsonData = JSON.parse(fs.readFileSync(jsonFile, 'utf8'));
  
  const htmlTemplate = `
  <!DOCTYPE html>
  <html>
  <head>
    <title>Debian系统性能测试报告</title>
    <style>
      body { font-family: Arial, sans-serif; margin: 20px; }
      h1, h2 { color: #333; }
      table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
      th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
      th { background-color: #f2f2f2; }
      .summary { background-color: #f9f9f9; padding: 15px; margin-bottom: 20px; }
      .section { margin-bottom: 30px; }
    </style>
  </head>
  <body>
    <h1>Debian系统性能测试报告</h1>
    <p>测试时间: ${new Date().toLocaleString()}</p>
    
    <div class="section">
      <h2>系统信息</h2>
      <table>
        <tr><th>项目</th><th>值</th></tr>
        <tr><td>操作系统</td><td>${jsonData.systemInfo.os}</td></tr>
        <tr><td>平台</td><td>${jsonData.systemInfo.platform}</td></tr>
        <tr><td>架构</td><td>${jsonData.systemInfo.arch}</td></tr>
        <tr><td>Debian版本</td><td>${jsonData.systemInfo.debianVersion}</td></tr>
        <tr><td>总内存</td><td>${(jsonData.systemInfo.totalMem / 1024 / 1024).toFixed(2)} MB</td></tr>
        <tr><td>CPU核心数</td><td>${jsonData.systemInfo.cpus.length}</td></tr>
        <tr><td>CPU型号</td><td>${jsonData.systemInfo.cpus[0].model}</td></tr>
      </table>
    </div>
    
    <div class="section">
      <h2>测试摘要</h2>
      <div class="summary">
        <p><strong>CPU平均执行时间:</strong> ${jsonData.summary.cpu.averageTime ? jsonData.summary.cpu.averageTime.toFixed(2) : 'N/A'} ms</p>
        <p><strong>CPU平均操作频率:</strong> ${jsonData.summary.cpu.averageHz ? jsonData.summary.cpu.averageHz.toFixed(2) : 'N/A'} ops/sec</p>
        <p><strong>内存平均分配时间:</strong> ${jsonData.summary.memory.averageTime ? jsonData.summary.memory.averageTime.toFixed(2) : 'N/A'} ms</p>
        <p><strong>磁盘平均写入速度:</strong> ${jsonData.summary.disk.averageSpeed ? jsonData.summary.disk.averageSpeed.toFixed(2) : 'N/A'} MB/s</p>
        <p><strong>网络平均延迟:</strong> ${jsonData.summary.network.averageLatency ? jsonData.summary.network.averageLatency.toFixed(2) : 'N/A'} ms</p>
        <p><strong>HTTP请求吞吐量:</strong> ${jsonData.summary.load.averageRPS ? jsonData.summary.load.averageRPS.toFixed(2) : 'N/A'} req/s</p>
      </div>
    </div>
    
    <div class="section">
      <h2>详细测试结果</h2>
      
      <h3>CPU性能测试</h3>
      <table>
        <tr><th>测试名称</th><th>结果</th><th>单位</th></tr>
        ${jsonData.cpuTests.map(test => `
          <tr>
            <td>${test.name}</td>
            <td>${test.time ? test.time.toFixed(2) : test.hz ? test.hz.toFixed(2) : JSON.stringify(test.stats)}</td>
            <td>${test.unit || 'N/A'}</td>
          </tr>
        `).join('')}
      </table>
      
      <h3>内存性能测试</h3>
      <table>
        <tr><th>测试名称</th><th>结果</th><th>单位</th></tr>
        ${jsonData.memoryTests.map(test => `
          <tr>
            <td>${test.name}</td>
            <td>${test.time ? test.time.toFixed(2) : test.leakedBytes ? test.leakedBytes : JSON.stringify(test.memoryUsage)}</td>
            <td>${test.unit || 'N/A'}</td>
          </tr>
        `).join('')}
      </table>
      
      <h3>磁盘I/O性能测试</h3>
      <table>
        <tr><th>测试名称</th><th>结果</th><th>单位</th></tr>
        ${jsonData.diskTests.map(test => `
          <tr>
            <td>${test.name}</td>
            <td>${test.time ? test.time.toFixed(2) : test.speed ? test.speed.toFixed(2) : 'N/A'}</td>
            <td>${test.unit || 'N/A'}</td>
          </tr>
        `).join('')}
      </table>
      
      <h3>网络性能测试</h3>
      <table>
        <tr><th>测试名称</th><th>结果</th><th>单位</th></tr>
        ${jsonData.networkTests.map(test => `
          <tr>
            <td>${test.name}</td>
            <td>${test.latency ? test.latency.toFixed(2) : test.throughput ? test.throughput.toFixed(2) : test.requests}</td>
            <td>${test.unit ? (typeof test.unit === 'object' ? test.unit.latency : test.unit) : 'N/A'}</td>
          </tr>
        `).join('')}
      </table>
      
      <h3>系统综合负载测试</h3>
      <table>
        <tr><th>测试名称</th><th>结果</th><th>单位</th></tr>
        ${jsonData.loadTests.map(test => `
          <tr>
            <td>${test.name}</td>
            <td>${test.requestsPerSecond ? test.requestsPerSecond.toFixed(2) : test.duration ? test.duration.toFixed(2) : 'N/A'}</td>
            <td>${test.unit || 'N/A'}</td>
          </tr>
        `).join('')}
      </table>
    </div>
  </body>
  </html>
  `;
  
  fs.writeFileSync(htmlReportFile, htmlTemplate);
  console.log(`HTML报告已保存到: ${htmlReportFile}`);
}

// 主函数
async function main() {
  try {
    console.log('开始Debian系统性能测试...');
    
    // 收集系统信息
    collectSystemInfo();
    
    // 运行各项测试
    await runCpuTests();
    runMemoryTests();
    await runDiskTests();
    await runNetworkTests();
    await runLoadTests();
    
    // 生成报告
    generateReport();
    
    console.log('性能测试完成!');
  } catch (error) {
    console.error('测试过程中发生错误:', error);
  }
}

// 执行主函数
main();

使用说明

1. 安装依赖

在运行测试程序前,需要安装以下依赖:

# 安装Node.js和npm(如果尚未安装)
sudo apt update
sudo apt install -y nodejs npm

# 安装系统工具
sudo apt install -y stress-ng wrk apache2-utils

# 安装Node.js依赖
npm install benchmark autocannon faker axios

2. 运行测试

将上述代码保存为debian-performance-test.js,然后运行:

node debian-performance-test.js

3. 测试结果

测试完成后,程序会在reports目录下生成两个文件:

  • performance-report-<timestamp>.json:详细的 JSON 格式测试结果

  • performance-report-<timestamp>.html:HTML 格式的可视化报告

测试内容详解

1. CPU性能测试

  • 素数计算:计算 0-50000 范围内的素数,测试 CPU 整数运算能力

  • 浮点运算:执行 1000 万次浮点运算,测试 CPU 浮点运算能力

  • 正则表达式与字符串操作:使用 Benchmark.js 测试基本操作性能

2. 内存性能测试

  • 内存分配:分配 100 万个 UUID 字符串,测试内存分配速度

  • 内存复制:复制 100 万元素数组,测试内存操作性能

  • 内存泄漏检测:故意创建内存泄漏,测试内存管理能力

3. 磁盘I/O性能测试

  • 顺序写入:写入 10 万个文本段落,测试磁盘写入性能

  • 顺序读取:读取 1 万个文本段落,测试磁盘读取性能

  • dd 命令测试:使用系统工具测试原始磁盘速度

4. 网络性能测试

  • 本地 HTTP 服务器:使用 autocannon 测试本地 HTTP 服务器性能

  • 外部网络延迟:测试访问 Google、GitHub 等外部网站的延迟

  • 高并发测试:使用 wrk 工具进行高并发 HTTP 测试

5. 系统综合负载测试

  • stress-ng 测试:使用 stress-ng 工具对 CPU、内存、I/O 进行综合压力测试

  • wrk 测试:模拟高并发 HTTP 请求,测试系统在高负载下的表现

测试报告解读

生成的 HTML 报告包含以下部分:

  1. 系统信息:显示测试环境的硬件和软件配置

  2. 测试摘要:各项测试的平均性能指标

  3. 详细测试结果

    • CPU 性能测试结果

    • 内存性能测试结果

    • 磁盘 I/O 性能测试结果

    • 网络性能测试结果

    • 系统综合负载测试结果

对比Debian 12和13性能

要对比 Debian 12 和 13 的性能,可以分别在两个系统上运行此测试程序,然后比较生成的报告。重点关注以下指标:

  1. CPU 性能:素数计算和浮点运算的时间差异

  2. 内存性能:内存分配和复制的速度差异

  3. 磁盘 I/O:顺序读写速度和 dd 命令测试结果

  4. 网络性能:HTTP 请求吞吐量和外部网络延迟

  5. 综合负载:stress-ng 和 wrk 测试结果

通过对比这些指标,可以全面评估 Debian 12 和 13 在各项性能上的差异。

注意事项

  1. 测试环境:确保测试环境一致,硬件配置相同

  2. 系统负载:测试时关闭不必要的应用程序,避免干扰

  3. 多次测试:建议多次运行测试取平均值,减少偶然误差

  4. 安全性:部分测试可能会对系统造成高负载,不要在生产环境运行

  5. 依赖安装:确保所有依赖工具正确安装

这个东西能够全面评估 Debian 系统的性能表现,特别适合对比不同版本间的性能差异。


Debian 12与13系统性能暴力测试代码
https://uniomo.com/archives/debian-12yu-13xi-tong-xing-neng-bao-li-ce-shi-dai-ma
作者
雨落秋垣
发布于
2025年12月15日
许可协议