SpringBoot StopWatch 统计耗时

统计耗时

    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Thread.sleep(2000);
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

单个线程使用StopWatch要多次计算执行时间

    public static void main(String[] args) {
        StopWatch stopWatch = new StopWatch();
        for (int i = 0; i < 5; i++) {
            stopWatch.start("stopWatch"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stopWatch.stop();
        }
        System.out.println("stopWatch task count :"+stopWatch.getTaskCount());
        System.out.println("总耗时:"+stopWatch.getTotalTimeSeconds()+"秒");
        for (StopWatch.TaskInfo taskInfo : stopWatch.getTaskInfo()) {
            System.out.println(taskInfo.getTaskName()+"耗时:"+taskInfo.getTimeSeconds()+"秒");
        }
    }

StopWatch 的属性

https://juejin.cn/post/6892785677637779469

    /**
	 * Identifier of this stop watch.
	 * Handy when we have output from multiple stop watches
	 * and need to distinguish between them in log or console output.
	 * 本实例的唯一 Id,用于在日志或控制台输出时区分的。
	 */
	private final String id;

	/**
	 * 是否保持一个 taskList 链表
	 * 每次停止计时时,会将当前任务放入这个链表,用以记录任务链路和计时分析
	 */
	private boolean keepTaskList = true;

	/** 任务链表 */
	private final List<TaskInfo> taskList = new LinkedList<>();

	/** Start time of the current task. */
	/** 当前任务的开始时间. */
	private long startTimeNanos;

	/** Name of the current task. */
	/** 当前任务名称. */
	@Nullable
	private String currentTaskName;

	@Nullable
	/** 最后一个任务的信息. */
	private TaskInfo lastTaskInfo;
	/** 任务总数. */
	private int taskCount;
	/** Total running time. */
	/** 总任务时间. */
	private long totalTimeNanos;

StopWatch 的其他用法

下面给大家提供几个思路。

1.在 Controller 层或 Service 层将 StopWatch 放入 ThreadLocal 当中。在整条 Service 调用链中,使用同一个 StopWatch 对象记录方法调用的耗时和路线。最后在结束时生成方法的耗时占比,以定位性能瓶颈。

2.利用 Spring-AOP 方式,在每个方法的开始和结束使用 StopWatch 记录接口耗时时间。

3.声明一个注解,利用 Spring-AOP 和注解的方式,自定义分析带注解的方法耗时。

在这几种情况下,3.1 章节中所说的任务调用链路就非常重要了。这个调用链路将是定位耗时的非常重要的手段。

StopWatch 的优缺点

相关地址

StopWatch 计算接口时间
https://juejin.cn/post/6892785677637779469

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值