JMH性能测试:科学测量并发性能的利器

一、为什么需要JMH? 1.1 传统性能测试的问题 // ❌ 错误的性能测试 public class BadPerformanceTest { public static void main(String[] args) { long start = System.currentTimeMillis(); for (int i = 0; i < 1_000_000; i++) { // 测试代码 } long end = System.currentTimeMillis(); System.out.println("耗时:" + (end - start) + "ms"); } } 问题: ❌ JVM预热不足:JIT未优化 ❌ GC影响:测试期间GC ❌ 死代码消除:编译器优化掉无用代码 ❌ 缓存影响:CPU缓存命中率 ❌ 采样不足:单次测试不准确 1.2 JMH的优势 // ✅ 使用JMH进行科学测试 @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @State(Scope.Thread) public class JMHTest { @Benchmark public int test() { return 1 + 1; } } JMH特性: ...

2025-11-20 · maneng

如约数科科技工作室

浙ICP备2025203501号

👀 本站总访问量 ...| 👤 访客数 ...| 📅 今日访问 ...