你是一名 JAVA 程序员现在要通过打印时间检查方法执行时长作为一名 Java 程序员检查方法执行时长是性能调优和排查慢接口最常用的手段。根据你的需求我为你整理了从最简单的手动打印到生产级 AOP 切面统计的几种主流方案。️ 方案一基础手动打印 (最简单)适用于临时调试或简单的脚本。注意请务必使用System.nanoTime()而不是System.currentTimeMillis()。前者是用于测量经过时间的后者是用于测量绝对时间的受系统时钟调整影响。publicvoidsimpleMethod(){longstartTimeSystem.nanoTime();// --- 模拟业务逻辑 ---try{Thread.sleep(500);}catch(InterruptedExceptione){e.printStackTrace();}// ------------------longendTimeSystem.nanoTime();// 转换为毫秒longdurationMs(endTime-startTime)/1_000_000;System.out.println(方法执行耗时: durationMs ms);}⏱️ 方案二使用 Google GuavaStopwatch(推荐)如果你的项目中引入了 Guava 库使用Stopwatch会让代码更优雅、可读性更强且不容易出错。Maven 依赖:dependencygroupIdcom.google.guava/groupIdartifactIdguava/artifactIdversion31.1-jre/version/dependency代码示例:importcom.google.common.base.Stopwatch;importjava.util.concurrent.TimeUnit;publicvoidguavaMethod(){StopwatchstopwatchStopwatch.createStarted();// --- 模拟业务逻辑 ---doSomething();// ------------------stopwatch.stop();System.out.println(方法执行耗时: stopwatch.elapsed(TimeUnit.MILLISECONDS) ms);} 方案三使用 Spring AOP 统计 (生产环境常用)在实际开发中我们通常不希望把计时代码侵入到每个业务方法里。使用 Spring AOP 可以无侵入地统计所有 Controller 或 Service 方法的耗时。适用场景统计接口响应时间排查慢 SQL 或慢方法。1. 定义一个自定义注解Target(ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)publicinterfaceLogExecutionTime{}2. 编写切面 (Aspect)importlombok.extern.slf4j.Slf4j;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.springframework.stereotype.Component;AspectComponentSlf4jpublicclassExecutionTimeAspect{Around(annotation(LogExecutionTime))publicObjectlogExecutionTime(ProceedingJoinPointjoinPoint)throwsThrowable{longstartSystem.nanoTime();try{returnjoinPoint.proceed();}finally{longendSystem.nanoTime();longduration(end-start)/1_000_000;// 打印类名、方法名和耗时log.info({} 方法执行耗时: {} ms,joinPoint.getSignature().toShortString(),duration);}}}3. 使用只需在方法上加上LogExecutionTime即可LogExecutionTimepublicUsergetUserById(Longid){// 业务逻辑returnuserRepository.findById(id);} 方案四使用 Java 8Duration(代码风格现代)如果你使用的是 Java 8可以使用java.time包下的类来处理时间差代码语义更清晰。importjava.time.Duration;importjava.time.Instant;publicvoidjava8Method(){InstantstartInstant.now();// --- 模拟业务逻辑 ---doSomething();// ------------------InstantendInstant.now();DurationdurationDuration.between(start,end);System.out.println(方法执行耗时: duration.toMillis() ms);} 核心建议总结精度选择始终优先使用System.nanoTime()因为它不受系统时间同步NTP的影响保证单调递增。日志框架在生产环境中不要使用System.out.println请使用日志框架如 SLF4J Logback/Log4j2以便管理日志级别和输出格式。性能分析如果需要更深入的火焰图分析查看 CPU 热点建议使用JProfiler或Arthas等专业的 Java 诊断工具而不是单纯依靠打印时间。
你是一名 JAVA 程序员,现在要通过打印时间检查方法执行时长
你是一名 JAVA 程序员现在要通过打印时间检查方法执行时长作为一名 Java 程序员检查方法执行时长是性能调优和排查慢接口最常用的手段。根据你的需求我为你整理了从最简单的手动打印到生产级 AOP 切面统计的几种主流方案。️ 方案一基础手动打印 (最简单)适用于临时调试或简单的脚本。注意请务必使用System.nanoTime()而不是System.currentTimeMillis()。前者是用于测量经过时间的后者是用于测量绝对时间的受系统时钟调整影响。publicvoidsimpleMethod(){longstartTimeSystem.nanoTime();// --- 模拟业务逻辑 ---try{Thread.sleep(500);}catch(InterruptedExceptione){e.printStackTrace();}// ------------------longendTimeSystem.nanoTime();// 转换为毫秒longdurationMs(endTime-startTime)/1_000_000;System.out.println(方法执行耗时: durationMs ms);}⏱️ 方案二使用 Google GuavaStopwatch(推荐)如果你的项目中引入了 Guava 库使用Stopwatch会让代码更优雅、可读性更强且不容易出错。Maven 依赖:dependencygroupIdcom.google.guava/groupIdartifactIdguava/artifactIdversion31.1-jre/version/dependency代码示例:importcom.google.common.base.Stopwatch;importjava.util.concurrent.TimeUnit;publicvoidguavaMethod(){StopwatchstopwatchStopwatch.createStarted();// --- 模拟业务逻辑 ---doSomething();// ------------------stopwatch.stop();System.out.println(方法执行耗时: stopwatch.elapsed(TimeUnit.MILLISECONDS) ms);} 方案三使用 Spring AOP 统计 (生产环境常用)在实际开发中我们通常不希望把计时代码侵入到每个业务方法里。使用 Spring AOP 可以无侵入地统计所有 Controller 或 Service 方法的耗时。适用场景统计接口响应时间排查慢 SQL 或慢方法。1. 定义一个自定义注解Target(ElementType.METHOD)Retention(RetentionPolicy.RUNTIME)publicinterfaceLogExecutionTime{}2. 编写切面 (Aspect)importlombok.extern.slf4j.Slf4j;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.springframework.stereotype.Component;AspectComponentSlf4jpublicclassExecutionTimeAspect{Around(annotation(LogExecutionTime))publicObjectlogExecutionTime(ProceedingJoinPointjoinPoint)throwsThrowable{longstartSystem.nanoTime();try{returnjoinPoint.proceed();}finally{longendSystem.nanoTime();longduration(end-start)/1_000_000;// 打印类名、方法名和耗时log.info({} 方法执行耗时: {} ms,joinPoint.getSignature().toShortString(),duration);}}}3. 使用只需在方法上加上LogExecutionTime即可LogExecutionTimepublicUsergetUserById(Longid){// 业务逻辑returnuserRepository.findById(id);} 方案四使用 Java 8Duration(代码风格现代)如果你使用的是 Java 8可以使用java.time包下的类来处理时间差代码语义更清晰。importjava.time.Duration;importjava.time.Instant;publicvoidjava8Method(){InstantstartInstant.now();// --- 模拟业务逻辑 ---doSomething();// ------------------InstantendInstant.now();DurationdurationDuration.between(start,end);System.out.println(方法执行耗时: duration.toMillis() ms);} 核心建议总结精度选择始终优先使用System.nanoTime()因为它不受系统时间同步NTP的影响保证单调递增。日志框架在生产环境中不要使用System.out.println请使用日志框架如 SLF4J Logback/Log4j2以便管理日志级别和输出格式。性能分析如果需要更深入的火焰图分析查看 CPU 热点建议使用JProfiler或Arthas等专业的 Java 诊断工具而不是单纯依靠打印时间。