Java8如何优雅的记录代码运行时间

2025-05-14 10:39:49 185
魁首哥

在日常后端开发中,性能优化是一项核心任务。我们经常需要测量某段代码的执行耗时,例如查询耗时、接口响应时间、批处理任务处理时间等。在 java 中,传统的做法可能是使用 system.currenttimemillis():

long start = system.currenttimemillis();
// 业务逻辑
long end = system.currenttimemillis();
system.out.println("执行耗时: " + (end - start) + "ms");

虽然这非常直接,但在 java 8 引入 java.time 包之后,我们可以使用更现代、更语义化的方式 —— instant 和 duration 来实现这一目标。

本文将带你深入了解 java 8 中几种记录代码运行时间的优雅方式,并附上实用工具类与建议,提高你的代码可读性与复用性。

java 8 简单实现方式

java 8 中的 java.time.instant 表示一个时间点,duration 表示两个时间点之间的时长:

import java.time.duration;
import java.time.instant;

public class sampletimer {
    public static void main(string[] args) {
        instant start = instant.now();

        // 模拟业务逻辑
        executebusinesslogic();

        instant end = instant.now();
        long timeelapsed = duration.between(start, end).tomillis();
        system.out.println("执行耗时: " + timeelapsed + " ms");
    }

    private static void executebusinesslogic() {
        try {
            thread.sleep(500); // 模拟耗时操作
        } catch (interruptedexception e) {
            thread.currentthread().interrupt();
        }
    }
}

相比 system.currenttimemillis(),这种写法更具可读性和表达力,并且跨平台表现一致(system.currenttimemillis 可能受系统时间调整影响)。

封装计时工具类(更通用 & 可复用)

为了更好地管理运行时间测量代码,我们可以封装一个小型工具类,例如 timerutils:

import java.time.duration;
import java.time.instant;
import java.util.function.supplier;

public class timerutils {

    public static  t measure(string taskname, supplier supplier) {
        instant start = instant.now();
        try {
            return supplier.get();
        } finally {
            instant end = instant.now();
            long duration = duration.between(start, end).tomillis();
            system.out.printf("【任务: %s】耗时: %d ms%n", taskname, duration);
        }
    }

    public static void measure(string taskname, runnable runnable) {
        instant start = instant.now();
        try {
            runnable.run();
        } finally {
            instant end = instant.now();
            long duration = duration.between(start, end).tomillis();
            system.out.printf("【任务: %s】耗时: %d ms%n", taskname, duration);
        }
    }
}

使用方式如下:

public class timerutilstest {
    public static void main(string[] args) {
        // 没有返回值
        timerutils.measure("执行任务a", () -> {
            try {
                thread.sleep(200);
            } catch (interruptedexception ignored) {}
        });

        // 有返回值
        string result = timerutils.measure("执行任务b", () -> {
            try {
                thread.sleep(300);
            } catch (interruptedexception ignored) {}
            return "任务完成";
        });

        system.out.println("任务b返回结果:" + result);
    }
}

这种封装方式可以很好地提升代码的可读性、复用性,尤其适合在 spring boot 项目中进行日志输出分析。

进阶使用:结合日志框架输出

实际项目中,推荐的做法是将耗时统计信息输出到日志中,便于统一采集和排查性能瓶颈。结合 slf4j + logback,可以这样集成:

private static final logger logger = loggerfactory.getlogger(myservice.class);

public void process() {
    instant start = instant.now();

    try {
        // 执行业务逻辑
    } finally {
        long elapsed = duration.between(start, instant.now()).tomillis();
        logger.info("处理接口耗时: {} ms", elapsed);
    }
}

比 system.out.println 更专业,也更便于后续 elk/prometheus 等监控系统采集。

使用 aop 自动记录方法执行时间(spring boot 推荐)

性能日志可以通过 spring aop 自动记录,无需在每个方法中手动添加计时代码:

1.自定义注解:

@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface timed {
    string value() default "";
}

2.编写切面类:

@aspect
@component
public class timingaspect {
    private static final logger logger = loggerfactory.getlogger(timingaspect.class);

    @around("@annotation(timed)")
    public object around(proceedingjoinpoint pjp, timed timed) throws throwable {
        instant start = instant.now();
        object result = pjp.proceed();
        long elapsed = duration.between(start, instant.now()).tomillis();

        string methodname = pjp.getsignature().toshortstring();
        logger.info("方法 [{}] 执行耗时: {} ms", methodname, elapsed);
        return result;
    }
}

使用示例:

@timed
public void handlerequest() {
    // 逻辑代码
}

优势:

  • 解耦业务逻辑与日志统计
    • 透明统一统计性能数据
    • 对 controller、service 层尤为实用

其他替代品推荐

除了 java 原生类,还有一些开源工具类也支持高效计时:

guava 的 stopwatch:

stopwatch stopwatch = stopwatch.createstarted();
// 执行代码
stopwatch.stop();
system.out.println("耗时: " + stopwatch.elapsed(timeunit.milliseconds) + "ms");

micrometer 和 spring boot actuator 提供的 @timed 注解和 metrics 接入更强大采集工具,如 prometheus、grafana。

总结

在注重性能的后端开发中,精准、高效地记录代码执行时间是不可或缺的一步。本文从 java 8 原生的 instant/duration 入手,展示了编写更优雅、规范、可扩展的代码计时方式。

方法优雅度可复用性推荐度
system.currenttimemillis一般
instant + duration良好
工具类封装✅✅
aop 自动化记录极高极高✅✅✅

到此这篇关于java8如何优雅的记录代码运行时间的文章就介绍到这了,更多相关java8记录代码运行时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

分享
海报
185
上一篇:SpringBoot捕获feign抛出异常的方法 下一篇:Java数组初始化的五种方式

忘记密码?

图形验证码