StopWatch

在日常的开发中我们需要统计一端代码的执行时间,我们可以这么做:

public static void main(String[] args) throws Exception {
       Long start = System.currentTimeMillis();
       Thread.sleep(1000);
       Long stop = System.currentTimeMillis();
       System.out.println("执行耗时:" + (stop - start));
   }

我在看springBoot源码的时候,看到了StopWatch,觉得好奇,跟进去看看源码,发现它也可以统计代码的执行耗时时间,看起来更加高大上,也更方便,我们看看它怎么使用:

public static void main(String[] args) throws Exception {
    StopWatch sw = new StopWatch();
    sw.start("t1");
    Thread.sleep(1000);
    sw.stop();
    sw.start("t2");
    Thread.sleep(2000);
    sw.stop();
    // 表格化输出
    System.out.println(sw.prettyPrint());
    System.out.println("***************************");
    //总结性输出
    System.out.println(sw.shortSummary());
    System.out.println("***************************");
    // 只输出耗时
    System.out.println(sw.getTotalTimeMillis());
}