SpringBoot 统计代码执行耗时时间

文章介绍了在Java中测量代码执行时间的四种常见方式:使用System.currentTimeMillis()获取毫秒级时间戳,用System.nanoTime()获取纳秒级精度的时间,通过newDate()创建日期对象计算差值,以及利用SpringUtil的StopWatch工具类进行详细的时间跟踪和任务耗时分析。StopWatch不仅提供基本的计时功能,还包括任务命名、任务数量统计和耗时详情打印等高级特性。
摘要由CSDN通过智能技术生成

第一种方式:System.currentTimeMillis()


@Test
public void test1() throws Exception{
    long start = System.currentTimeMillis();
    Thread.sleep(5);
    long end = System.currentTimeMillis();
    System.out.println(end -start);
}

第二种方式: System.nanoTime()


@Test
public void test2() throws Exception{
    long start = System.nanoTime();
    Thread.sleep(5);
    long end = System.nanoTime();
    //注意单位:1秒等于100万纳秒
    System.out.println(end -start);
}

第三种方式:new Date()


@Test
public void test3() throws Exception{
    Date start = new Date();
    Thread.sleep(5);
    Date end = new Date();
    System.out.println(end.getTime() -start.getTime());
}

第四种方式:spring util 里面提供的StopWatch


@Test
public void test4() throws Exception{
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Thread.sleep(5);
    stopWatch.stop();
    System.out.println(stopWatch.getTotalTimeMillis());
}

StopWatch 其实不仅仅是封了一下耗时统计,还有如下作用:

  • void start(“任务名称”):开始一个任务名称的计时

  • void stop():停止当前任务的计时

  • boolean isRunning():是否正在计时某任务

  • long getTotalTimeMillis():所有任务的总体执行时间(毫秒单位)

  • double getTotalTimeSeconds():所有任务的总时间(以秒为单位)

  • long getLastTaskTimeMillis():上一个任务的耗时(毫秒单位)

  • int getTaskCount():定时任务的数量

  • String prettyPrint():优美地打印所有任务的详细耗时情况

  • StopWatch.TaskInfo[] getTaskInfo():包含任务名称和任务耗时的实体类数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值