Java学习笔记-SLF4J中的Profilers的性能记录分析

最近经常滑水,没事就看看开发代码,又发现一处之前没接触过的知识(哎,学习是无止境的),发现了Profilers的用法。

 

1.Profilers的作用

摘抄于百度:阶段性的记录日志,并打印出各个阶段所耗费的时间,可用于性能分析之类的

 

2.用法

说明:

1.引入依赖,看下面例子

2.new一个Profiler

3.调用start方法,开始进行性能记录

4.调用实际要运行的方法

5.重复3和4步骤

6.调用stop方法,打印profiler的内容(下面输出的Profiler【Sample】内容)

 

3.例子

在执行该例子前,要在依赖中导入

<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-ext</artifactId>
   <version>1.7.25</version>
</dependency>

 

以下例子摘抄于网络:https://my.oschina.net/u/160225/blog/4691386 

import org.slf4j.profiler.Profiler;
import org.slf4j.profiler.TimeInstrument;

/**
 * @Author: 一片蓝蓝的云
 * @Date: 2021/4/7
 */
public class ProfilerExample {
    public void demoMethod1(){
        double sum = 0;
        for(int i=0; i< 1000; i++){
            sum = sum+(Math.pow(i, 2));
        }
        System.out.println("Sum of squares of the numbers from 1 to 10000: "+sum);
    }

    public void demoMethod2(){
        int sum = 0;
        for(int i=0; i< 10000; i++){
            sum = sum+i;
        }
        System.out.println("Sum of the numbers from 1 to 10000: "+sum);
    }

    public static void main(String[] args) {
        ProfilerExample obj = new ProfilerExample();
        //Creating a profiler
        Profiler profiler = new Profiler("Sample");
        //Starting a child stop watch and stopping the previous one.
        profiler.start("Task 1");
        obj.demoMethod1();
        //Starting another child stop watch and stopping the previous one.
        profiler.start("Task 2");
        obj.demoMethod2();
        //Stopping the current child watch and the global watch.
        TimeInstrument tm = profiler.stop();
        //printing the contents of the time instrument
        tm.print();
    }
}

以下是执行情况

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值