StopWatch 监控时间用法

StopWatch 监控时间用法

// stopWatch 引入的jar包  org.springframework.util.StopWatch
// start 与 stop 是一一对应的, 如果想要在start与 stop中监控其他内容耗时,此时需要重新创建一个对象. 
//        不允许在同一个对象中连续start 两次, 否则会抛出异常(IllegalStateException)
try{
    Long sTime = System.currentTimeMillis();
    StopWatch sw = new StopWatch();
    sw.start("for循环");
    StringBuffer a = new StringBuffer();
    for (int i = 0; i < 10000000; i++){
        a = a.append(i);
        if(i == 10000){
            StopWatch sw1 = new StopWatch();
            sw1.start("5000");
            Thread.sleep(5000);
            sw1.stop();
            System.out.println(sw1.prettyPrint());
        }
    }
    sw.stop();

    sw.start("for循环2");
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < 10000000; i++){
        b = b.append(i);
        if(i == 10000){
            Thread.sleep(1000);
        }
    }
    sw.stop();
    Long eTime = System.currentTimeMillis();
    System.out.println("共耗时 : " + (eTime - sTime) + " 毫秒;");
    System.out.println(sw.prettyPrint());
}catch (Exception e){

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Stopwatch是一个计时器工具类,可以用来计算程序部分代码的执行时间。使用Stopwatch可以更方便地计算耗时,而不需要使用System.currentTimeMillis()来手动计算。以下是Stopwatch用法示例: 1. 创建Stopwatch实例: StopWatch stopWatch = new StopWatch("测试"); 2. 开始计时: stopWatch.start("任务1"); 3. 执行任务代码: // 执行任务1的代码 4. 停止计时: stopWatch.stop(); 5. 获取任务耗时: StopWatch.TaskInfo\[\] taskInfo = stopWatch.getTaskInfo(); for (StopWatch.TaskInfo info : taskInfo) { System.out.println(info.getTimeMillis()); } 6. 获取总体耗时: long totalTime = stopWatch.getTotalTimeMillis(); 7. 获取上一个任务的耗时: long lastTaskTime = stopWatch.getLastTaskTimeMillis(); 8. 格式化输出计时结果: String formattedTime = stopWatch.prettyPrint(); 9. 检查计时器是否在运行中: boolean isRunning = stopWatch.isRunning(); 请注意,Stopwatch实例一次只能开启一个任务,不能同时start多个任务。必须在一个任务stop之后才能开启新的任务。如果需要同时开启多个任务,需要创建不同的Stopwatch实例。 以上是Stopwatch的基本用法,你可以根据需要进行相应的调整和扩展。 #### 引用[.reference_title] - *1* [Stopwatch用法](https://blog.csdn.net/qq_38261544/article/details/120333259)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [springboot学习(七十四) spring中时钟计时器StopWatch的使用](https://blog.csdn.net/u011943534/article/details/128219115)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值