stopwatch 依赖_Spring框架中的stopWatch

本文介绍了如何利用Spring框架中的StopWatch工具类来便捷地计算代码执行时间,对比了传统的计时方式,并通过示例代码展示了StopWatch在统计多个任务耗时上的便利性。在示例中,StopWatch分别计时了两个任务的执行,最后输出了详细的耗时信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

b80f1b790794b4c1eeaef14acda2048d.png

今天分享的是Spring框架中的一个工具类,可以说成是一个计时器吧。如有不足,敬请指正。

一、传统计时方式

我们之前比如统计一个方法执行的时间通常都是:

long startTime = System.currentTimeMillis();

// 业务代码

long endTime = System.currentTimeMillis();

long costTime = endTime -startTime;

System.err.println("该段代码耗时:" + costTime + " ms");

二、使用stopWatch

我们在使用Spring自带的工具类后可以很方便的计算出任务的耗时,直接上代码

package com.rrs.ktransfer.milkytea.test;

import com.rrss.ktransfer.milkytea.MilkyTeaApplication;

import org.junit.runner.RunWith;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.util.StopWatch;

/**

* Created by lzx on 2019/8/17.

*/

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes = MilkyTeaApplication.class)

public class StopWatchTest {

public static void main(String[] args) throws InterruptedException {

StopWatch stopWatch = new StopWatch("统计一组任务耗时");

// 统计任务一耗时

stopWatch.start("任务一");

Thread.sleep(1000);

stopWatch.stop();

// 统计任务二耗时

stopWatch.start("任务二");

Thread.sleep(2000);

stopWatch.stop();

// 打印出耗时

String result = stopWatch.prettyPrint();

System.err.println(result);

}

}

运行结果如下:

08ebfef82cb3be2c9a4506318dfb748e.png

版权说明:欢迎以任何方式进行转载,但请在转载后注明出处!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值