• java记录程序执行时间之StopWatch


    在日常写代码的过程中,通常会记录某一段程序的运行时间,使用的方式是System.currentTimeMillis()。

    Spring也自带了一种方式StopWatch,使用起来也比较简单。

    共分为四步:创建对象,开始记录执行时间,结束记录执行时间,获取执行的总时间。

    package com.zys.example;
    
    import org.springframework.util.StopWatch;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class AppMain {
        public static void main(String[] args) {
            StopWatch watch = new StopWatch();
            watch.start();
            List<String> list = new ArrayList<>();
            for (int i = 0; i < 100000; i++) {
                list.add("哈哈" + (i + 1));
            }
            watch.stop();
            System.out.println("用时(ms):" + watch.getTotalTimeMillis());//26
        }
    
    
    }

    上述代码是记录向集合中插入10万条数据所需要的时间,最后打印的结果是26ms,此时间是不固定的。相比于System.currentTimeMillis()无需计算两个时间差,显得更为方便。

    除此之外,还可以记录多个任务一共执行的时间,需要指定任务名称:

    public static void main(String[] args) throws InterruptedException {
            StopWatch watch = new StopWatch();
            watch.start("task1");
            Thread.sleep(200);
            watch.stop();
            watch.start("task2");
            Thread.sleep(5000);
            watch.stop();
            watch.start("task3");
            Thread.sleep(10);
            watch.stop();
            System.out.println("任务数用时:" + watch.getTotalTimeMillis() + " ms");
            System.out.println("任务数:" + watch.getTaskCount());
            System.out.println("任务执行的百分比:" + watch.prettyPrint());
        }

    执行结果如下:

  • 相关阅读:
    HDU 1495 非常可乐
    ja
    Codeforces Good Bye 2016 E. New Year and Old Subsequence
    The 2019 Asia Nanchang First Round Online Programming Contest
    Educational Codeforces Round 72 (Rated for Div. 2)
    Codeforces Round #583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)
    AtCoder Regular Contest 102
    AtCoder Regular Contest 103
    POJ1741 Tree(点分治)
    洛谷P2634 [国家集训队]聪聪可可(点分治)
  • 原文地址:https://www.cnblogs.com/zys2019/p/15844577.html
Copyright © 2020-2023  润新知