Total method time in Java VisualVM

前端 未结 7 889
野趣味
野趣味 2020-12-04 21:09

In Java VisualVM, is there any way to display total method time, rather than \"self time\"? (The latter is not particularly useful, since it doesn\'t tell you anything about

7条回答
  •  失恋的感觉
    2020-12-04 21:50

    JavaAssist is a class library to manipulate your Java Byte Code without touching the source. Let's take an example of measuring time taken to execute a method.

    public class Subject {
        /**
         * Timetaken for start & end of the method
         * 
         * @throws InterruptedException
         */
        public void method2() throws InterruptedException {
            // Some business logic :)
            Thread.sleep(2000);
        }
    }
    

    To measure time taken for executing subject.method2(), you could enhance the Subject.methods() by adding code start and end of the method as shown.

    public class JavaAssist {
        public static void main(String[] args) {
            timeTaken();
        }
    
        public static void timeTaken() {
            try {
                ClassPool p = ClassPool.getDefault();
                CtClass cc = p.get("Subject");
                CtMethod meth2 = cc.getDeclaredMethod("method2");
                meth2.insertBefore("System.out.println(\" Start : \"+new java.util.Date());");
                meth2.insertAfter("System.out.println(\" End : \"+new java.util.Date());");
                // cc.writeFile(".");
                Class c = cc.toClass();
                Subject s = (Subject) c.newInstance();
                s.method2();
                cc.detach();
            } catch (Exception e) {
                // suppressed
            }
        }
    }
    

    Output: Start : Wed May 26 17:24:18 EDT 2010 End : Wed May 26 17:24:20 EDT 2010

    Reference http://www.csg.is.titech.ac.jp/~chiba/javassist/tutorial/tutorial.html#read

    http://www.csg.is.titech.ac.jp/~chiba/javassist/html/

    Origin Post from: http://www.senthilb.com/2010/05/javaassist-byte-code-enhancement.html

提交回复
热议问题