perf4j使用一

perf4j使用一

如果大家使用的是maven工程,那么现在pom文件中加入perf4j的依赖。

<dependency>

<groupId>org.perf4j</groupId>

<artifactId>perf4j</artifactId>

<version>0.9.16</version>

<scope>compile</scope>

</dependency>

如果用的是普通工程,那么直接下载jar包放入lib目录下即可。

 

 

例子:

package com.baowu.per4j;

 

import org.perf4j.LoggingStopWatch;

import org.perf4j.StopWatch;

 

public class Example1 {

 

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

       method1();

       method2();

       method3();

    }

   

    /**

     * 监控一处代码示例

     * @throws InterruptedException

     */

    private static void method1() throws InterruptedException{

       //创建一个监控对象,这里使用LoggingStopWatch,它是把结果直接输出到控制台。我们也可以

       //使用StopWatch的其他子类,比如:Log4JStopWatchCommonsLogStopWatch。不过这些子类需

       //要工程使用日志框架

       StopWatch stopWatch = new LoggingStopWatch("codeBlock1");

 

       //这里就是一些需要监控的代码,我们命名为codeBlock1

       //使用线程休眠是为了模拟代码执行时间

       Thread.sleep((long)(Math.random() * 1000L));

 

       //停止计算代码性能

       stopWatch.stop();

    }

   

    /**

     * 一个方法多出代码监控

     * @throws InterruptedException

     */

    private static void method2() throws InterruptedException{

       StopWatch stopWatch = new LoggingStopWatch();

       Thread.sleep((long)(Math.random() * 1000L));

       stopWatch.lap("codeBlock3");

       Thread.sleep((long)(Math.random() * 1000L));

       stopWatch.lap("codeBlock4");

       Thread.sleep((long)(Math.random() * 1000L));

       stopWatch.lap("codeBlock5");

       Thread.sleep((long)(Math.random() * 1000L));

       stopWatch.stop("codeBlock6");

    }

   

    /**

     * stop方法可以加入一些说明信息

     */

    private static void method3(){

       StopWatch stopWatch = new LoggingStopWatch();

       try {

           // the code block being timed - this is just a dummy example

           long sleepTime = (long)(Math.random() * 1000L);

           Thread.sleep(sleepTime);

           if (sleepTime > 500L) {

               throw new Exception("Throwing exception");

           }

           stopWatch.stop("codeBlock2.success", "Sleep time was < 500 ms");

       } catch (Exception e) {

           stopWatch.stop("codeBlock2.failure", "Exception was: " + e);

       }

    }

}

 

运行结果:

start[1334457619937] time[355] tag[codeBlock1]

start[1334457620296] time[152] tag[codeBlock3]

start[1334457620453] time[138] tag[codeBlock4]

start[1334457620593] time[598] tag[codeBlock5]

start[1334457621187] time[700] tag[codeBlock6]

start[1334457621890] time[619] tag[codeBlock2.failure] message[Exception was: java.lang.Exception: Throwing exception]



你可能感兴趣的:(perf4j使用一)