java 打印调用方法用时

java 打印调用方法用时 在 Java 中打印方法调用耗时是性能分析和调试中的常见需求。以下是几种常用且实用的方法适用于不同场景1. 使用System.currentTimeMillis()毫秒级适用于粗略耗时统计long start System.currentTimeMillis(); // 执行方法 long end System.currentTimeMillis(); System.out.println(耗时: (end - start) ms);2. 使用System.nanoTime()纳秒级更精确适用于对精度要求较高的场景long start System.nanoTime(); // 执行方法 long end System.nanoTime(); System.out.println(耗时: (end - start) / 1_000_000.0 ms);3. 使用StopWatch工具类推荐Spring 的StopWatchimport org.springframework.util.StopWatch; StopWatch stopWatch new StopWatch(methodTimer); stopWatch.start(); // 执行方法 stopWatch.stop(); System.out.println(耗时: stopWatch.getTotalTimeMillis() ms);Apache Commons Lang 的StopWatchimport org.apache.commons.lang3.time.StopWatch; StopWatch stopWatch new StopWatch(); stopWatch.start(); // 执行方法 stopWatch.stop(); System.out.println(耗时: stopWatch.getTime() ms);4. 使用 AOP 切面自动统计所有方法适用于批量监控方法耗时无需手动添加代码Aspect Component public class MethodTimeAspect { Around(annotation(LogExecutionTime)) public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long start System.nanoTime(); Object result joinPoint.proceed(); long end System.nanoTime(); double duration (end - start) / 1_000_000.0; System.out.printf(%s 耗时: %.2f ms%n, joinPoint.getSignature().toShortString(), duration); return result; } } // 自定义注解 Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) public interface LogExecutionTime {}使用示例LogExecutionTime public void myMethod() { // 方法逻辑 }5. 使用函数式接口封装Java 8适用于灵活封装耗时逻辑public static T T measureTime(String label, SupplierT supplier) { long start System.nanoTime(); T result supplier.get(); long end System.nanoTime(); System.out.printf(%s 耗时: %.2f ms%n, label, (end - start) / 1_000_000.0); return result; } // 使用示例 String result measureTime(数据处理, () - { // 业务逻辑 return 完成; });6. 实用工具类可复用public class TimeUtil { public static void printTime(String label, Runnable task) { long start System.nanoTime(); task.run(); long end System.nanoTime(); System.out.printf(%s 耗时: %.2f ms%n, label, (end - start) / 1_000_000.0); } public static T T measureTime(String label, SupplierT supplier) { long start System.nanoTime(); T result supplier.get(); long end System.nanoTime(); System.out.printf(%s 耗时: %.2f ms%n, label, (end - start) / 1_000_000.0); return result; } }7. 方法对比与建议方法精度优点适用场景currentTimeMillis()毫秒简单、无需依赖粗略统计nanoTime()纳秒精度高性能敏感场景StopWatch毫秒/纳秒可读性强、支持多任务多段耗时统计AOP 切面纳秒自动统计、无侵入批量监控方法函数式接口/工具类封装纳秒灵活、可复用通用耗时测量注意事项生产环境建议使用日志框架如 SLF4J Logback替代System.out.println避免过度测量频繁打印会影响性能注意单位转换nanoTime()返回的是纳秒需转换为毫秒线程安全StopWatch不是线程安全的避免多线程共享根据你的具体需求选择合适的方法。如果是临时调试nanoTime()或工具类足够如果需要系统级监控建议使用 AOP 或集成性能分析工具如 Arthas、JProfiler。