当前位置:   article > 正文

Java学习笔记-SLF4J中的Profilers的性能记录分析_org.slf4j.profiler

org.slf4j.profiler

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

 

1.Profilers的作用

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

 

2.用法

说明:

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

2.new一个Profiler

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

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

5.重复3和4步骤

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

 

3.例子

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

  1. <dependency>
  2. <groupId>org.slf4j</groupId>
  3. <artifactId>slf4j-ext</artifactId>
  4. <version>1.7.25</version>
  5. </dependency>

 

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

  1. import org.slf4j.profiler.Profiler;
  2. import org.slf4j.profiler.TimeInstrument;
  3. /**
  4. * @Author: 一片蓝蓝的云
  5. * @Date: 2021/4/7
  6. */
  7. public class ProfilerExample {
  8. public void demoMethod1(){
  9. double sum = 0;
  10. for(int i=0; i< 1000; i++){
  11. sum = sum+(Math.pow(i, 2));
  12. }
  13. System.out.println("Sum of squares of the numbers from 1 to 10000: "+sum);
  14. }
  15. public void demoMethod2(){
  16. int sum = 0;
  17. for(int i=0; i< 10000; i++){
  18. sum = sum+i;
  19. }
  20. System.out.println("Sum of the numbers from 1 to 10000: "+sum);
  21. }
  22. public static void main(String[] args) {
  23. ProfilerExample obj = new ProfilerExample();
  24. //Creating a profiler
  25. Profiler profiler = new Profiler("Sample");
  26. //Starting a child stop watch and stopping the previous one.
  27. profiler.start("Task 1");
  28. obj.demoMethod1();
  29. //Starting another child stop watch and stopping the previous one.
  30. profiler.start("Task 2");
  31. obj.demoMethod2();
  32. //Stopping the current child watch and the global watch.
  33. TimeInstrument tm = profiler.stop();
  34. //printing the contents of the time instrument
  35. tm.print();
  36. }
  37. }

以下是执行情况

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/823444
推荐阅读
相关标签
  

闽ICP备14008679号