脚本如何对比不同版本性能差异

wen 实用脚本 32

本文目录导读:

脚本如何对比不同版本性能差异

  1. 基准测试环境准备
  2. 性能测量指标
  3. 具体测试方法
  4. 自动化对比脚本
  5. 可视化对比
  6. 高级分析技巧
  7. 注意事项
  8. 报告模板示例

要对比不同版本脚本的性能差异,可以采用多种方法和工具,以下是一个系统性的对比流程,涵盖从数据收集到分析的完整步骤:

基准测试环境准备

环境一致性

  • 相同硬件:CPU、内存、磁盘等保持一致
  • 相同操作系统:系统版本、内核参数一致
  • 相同依赖:库版本、环境变量相同
  • 隔离运行:避免后台进程干扰

脚本要求

  • 输入参数和功能完全一致
  • 输出结果逻辑相同
  • 测试数据相同(随机种子固定)

性能测量指标

指标 说明 工具示例
执行时间 总耗时 time (Unix)
内存使用 峰值/平均分配 ps, Valgrind massif
CPU使用率 用户态/系统态 htop, /usr/bin/time -v
I/O操作 读写次数/传输量 iostat, strace
系统调用 数量与类型 strace -c

具体测试方法

方法A:简单时间测量

# 多次运行取平均值
for i in {1..10}; do
    time python3 v1.py  # 或 python3 v2.py
done

Python示例

import timeit
import sys
# 测试不同版本的模块
def test_v1():
    # import v1_module or use exec
    pass
def test_v2():
    pass
# 运行多次取最小值
t1 = timeit.repeat(test_v1, number=1000, repeat=5)
t2 = timeit.repeat(test_v2, number=1000, repeat=5)
print(f"V1: min={min(t1):.4f}s, avg={sum(t1)/len(t1):.4f}s")
print(f"V2: min={min(t2):.4f}s, avg={sum(t2)/len(t2):.4f}s")

方法B:CPU Profiling

# Python
python3 -m cProfile -o v1.prof v1.py
python3 -m cProfile -o v2.prof v2.py
python3 -c "import pstats; p = pstats.Stats('v1.prof'); p.sort_stats('cumtime').print_stats(10)"
# Node.js
node --prof v1.js
node --prof-process isolate-*.log > v1-processed.txt

方法C:内存分析

# 使用 Valgrind (C/C++/Python)
valgrind --tool=massif --massif-out-file=massif.out.%p python3 v1.py
ms_print massif.out.12345
# Python 专用
pip install memory_profiler
python3 -m memory_profiler v1.py

自动化对比脚本

#!/usr/bin/env python3
"""性能对比框架"""
import subprocess
import time
import statistics
import sys
def run_test(cmd, iterations=10):
    """执行测试并返回时间列表"""
    times = []
    for i in range(iterations):
        start = time.time()
        result = subprocess.run(cmd, capture_output=True, text=True)
        end = time.time()
        times.append(end - start)
        # 验证输出一致性
        if i == 0:
            baseline_output = result.stdout
        elif result.stdout != baseline_output:
            print(f"Warning: Output mismatch at iteration {i}")
    return {
        'min': min(times),
        'max': max(times),
        'avg': statistics.mean(times),
        'median': statistics.median(times),
        'stddev': statistics.stdev(times) if len(times) > 1 else 0
    }
if __name__ == "__main__":
    v1_stats = run_test(["python3", "v1.py", "input_data"])
    v2_stats = run_test(["python3", "v2.py", "input_data"])
    print(f"{'Metric':<15} {'V1':<15} {'V2':<15} {'Change':<15}")
    print("-" * 60)
    for key in ['min', 'avg', 'median']:
        v1_val = v1_stats[key]
        v2_val = v2_stats[key]
        change = ((v2_val - v1_val) / v1_val) * 100
        print(f"{key:<15} {v1_val:<15.4f} {v2_val:<15.4f} {change:+.2f}%")

可视化对比

使用 matplotlib 生成图表

import matplotlib.pyplot as plt
import numpy as np
labels = ['V1', 'V2']
data = [v1_times, v2_times]  # 原始时间列表
fig, ax = plt.subplots(1, 2, figsize=(12, 5))
# 箱线图
ax[0].boxplot(data, labels=labels)
ax[0].set_title('执行时间分布')
ax[0].set_ylabel('时间 (秒)')
# 柱状图(平均值+标准差)
means = [np.mean(d) for d in data]
stds = [np.std(d) for d in data]
ax[1].bar(labels, means, yerr=stds, capsize=5)
ax[1].set_title('平均执行时间 (±标准差)')
ax[1].set_ylabel('时间 (秒)')
plt.tight_layout()
plt.savefig('performance_comparison.png')

高级分析技巧

统计显著性检验

from scipy import stats
# t检验判断性能差异是否显著
t_stat, p_value = stats.ttest_ind(v1_times, v2_times)
print(f"t统计量: {t_stat:.4f}, p值: {p_value:.4f}")
# p < 0.05 表示差异显著

编译语言的特殊考虑

对于 C/C++/Rust:

# 使用 perf (Linux)
perf stat -d ./v1
perf stat -d ./v2
# 对比缓存命中率
perf stat -e cache-references,cache-misses ./v1

注意事项

  1. 预热阶段:对于JIT编译的语言(Java/Node),忽略前几次执行
  2. GC影响:垃圾回收可能导致执行时间波动,考虑手动触发GC
  3. 输入规模:测试多种规模(小/中/大数据集)
  4. 系统负载:在系统空闲时运行,关闭守护进程
  5. 结果记录:保存原始数据便于复现

报告模板示例

## 性能对比报告
### 环境
- CPU: Intel i7-10700K @ 3.8GHz
- 内存: 32GB DDR4
- OS: Ubuntu 22.04 LTS
- Python 3.10.12
### 结果
| 指标 | V1 | V2 | 变化 |
|------|----|----|------|
| 平均耗时 | 2.31s | 1.89s | -18.2% |
| 峰值内存 | 456MB | 423MB | -7.2% |
| 99th延迟 | 2.45s | 2.01s | -17.9% |
### 
V2在各项指标上均有优化,建议采用新版。

通过以上系统性的方法,你可以得到科学、可靠且可重现的性能对比结果,根据脚本的具体类型(计算密集型、I/O密集型等),选择合适的测量指标和工具尤为重要。

抱歉,评论功能暂时关闭!