程序监控之StopWatch

StopWatch 是 属于 spring core 下的:

 org.springframework.util.StopWatch

 StopWatch可以监控多个任务执行,并且可以分别打印出消耗的时间,还提供了线程名自定义的操作。

例子:

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

        // id 可以随意修改,最好使用唯一性的ID 方便日志分析
        String id = UUID.randomUUID().toString();
        System.out.println("id:" + id);
        // 最好使用StopWatch(string id)的方法 后续可以更好的分析监控
        // StopWatch 还提供了StopWatch()的方法,虽然作用一样 但是不推荐使用
        StopWatch sw = new StopWatch(id);

        sw.start("我要吃饭");
        Thread.sleep(200);
        System.out.println("当前任务名称:" + sw.currentTaskName());
        sw.stop();

        sw.start("我去上班");
        Thread.sleep(1000);
        System.out.println("当前任务名称:" + sw.currentTaskName());
        sw.stop();

        System.out.println("---------0----------");
        //  这个方法 包含下边的sw.shortSummary(),
        // 打印出了执行任务的ID 执行需要的时间  任务名  时间占比
        System.out.println(sw.prettyPrint());
        System.out.println("---------1----------");
        System.out.println(sw.shortSummary());
        System.out.println("---------2----------");
        // stop后它的值为null
        System.out.println(sw.currentTaskName());
        System.out.println("---------3---------");

        // 最后一个任务的相关信息
        System.out.println(sw.getLastTaskName());
        System.out.println("---------4---------");
        System.out.println(sw.getLastTaskInfo());
        System.out.println("---------5---------");
        // 任务总的耗时  如果你想获取到每个任务详情(包括它的任务名、耗时等等)可使用
        System.out.println("所有任务总耗时:" + sw.getTotalTimeMillis());
        System.out.println("任务总数:" + sw.getTaskCount());
        System.out.println("所有任务详情:" + sw.getTaskInfo()); // 拿到所有的任务
    }

执行结果:

id:42fe909c-61c6-471b-b9fd-2d70df813981
当前任务名称:我要吃饭
当前任务名称:我去上班
---------0----------
StopWatch '42fe909c-61c6-471b-b9fd-2d70df813981': running time = 1207478300 ns
---------------------------------------------
ns         %     Task name
---------------------------------------------
204081500  017%  我要吃饭
1003396800  083%  我去上班

---------1----------
StopWatch '42fe909c-61c6-471b-b9fd-2d70df813981': running time = 1207478300 ns
---------2----------
null
---------3---------
我去上班
---------4---------
org.springframework.util.StopWatch$TaskInfo@3339ad8e
---------5---------
所有任务总耗时:1207
任务总数:2
所有任务详情:[Lorg.springframework.util.StopWatch$TaskInfo;@555590

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值