spring使用一种优雅的计时方式

1、在程序开发过程中,我们常常需要计算某段程序的运行时间,来衡量程序的执行性能,常见的计时方式时在程序开始的地方记录程序运行到此处的时间戳,然后在程序结尾的时候记录程序运行到结尾的时间戳,两个时间戳相减即为程序运行所花费的时间,这种办法并没有什么问题,而且很实用,就是有点不美观,今天介绍spring的一种比较优雅的实现方式-StopWatch

2、之前的实现方式

package com.llg.mybatis;

public class TestCountTime {

    public static void main(String[] args) {
        long t1 = System.currentTimeMillis();
        int i = doSomeThing(10000);
        long t2 = System.currentTimeMillis();
        System.out.println("耗时:" + (t2 - t1) + "ms");
    }



    private static int doSomeThing(int n){
        int sum = 0;
        for (int i = 0; i < n; i++){
            for(int j = 0; j < n - 1; j++){
                sum += i - j;
            }
        }
        return sum;
    }


}

3、比较优雅的方式,只需引入spring的核心包


    org.springframework
    spring-core
    ${spring.version}
package com.szkingdom.test;

import org.springframework.util.StopWatch;

public class TestCountTime {

    public static void main(String[] args) {
        StopWatch clock = new StopWatch();
        clock.start("任务一");
        int i = doSomeThing(10000);
        clock.stop();

        clock.start("任务二");
        int j = doSomeThing(10000);
        clock.stop();
        System.out.println(clock.prettyPrint());
    }



    private static int doSomeThing(int n){
        int sum = 0;
        for (int i = 0; i < n; i++){
            for(int j = 0; j < n - 1; j++){
                sum += i - j;
            }
        }
        return sum;
    }


}
clock.prettyPrint()可以以比较优美的格式打印出每个任务的运行时间和百分比

spring使用一种优雅的计时方式_第1张图片

 

你可能感兴趣的:(java,java)