java how can I measure method call times?

你说的曾经没有我的故事 提交于 2020-01-24 21:26:41

问题


I have a simple class and I would like to measure method call times how can I do that? Looking for generic way to achieve that so I can apply it to more difficult classes as well. Thank you

import java.io.*;
import java.util.*; 

public class Turtle {
  private String name;
  private Formatter f;
  public Turtle(String name, Formatter f) {
    this.name = name;
    this.f = f;
  }

  public void move(int x, int y) {
    f.format("%s The Turtle is at (%d,%d)\n", name, x, y);
  }

  public static void main(String[] args) {
    PrintStream outAlias = System.err;
    Turtle tommy = new Turtle("Tommy",
      new Formatter(System.out));
    Turtle terry = new Turtle("Terry",
      new Formatter(outAlias));
    tommy.move(0,0);
    terry.move(4,8);
    tommy.move(3,4);
    terry.move(2,5);
    tommy.move(3,3);
    terry.move(3,3);
  }
}

回答1:


Use dedicated tools that will show You even more You need :) VisualVM is best one in my opinion, However there are other available (e.g. JConsole that is provided in JDK natively, or JRockit that is paid).
Read more here on my post

These tools shows running apps and resources consumed by them along with servlets (if any) processing times, error and call counts etc. Also threads and classes instantiated are listed. This will surely satisfy Your needs




回答2:


Use either a profiler or count them manually:

public static int MOVE_CALL_COUNT;


public void move(int, int)
{
    MOVE_CALL_COUNT++;
}

Profiling is recommended. In NetBeans there is a built-in profiler. Otherwise, VisualVM is a recommended option, which is the same profiler as in NetBeans.

If you really want to know how long it takes to run these methods, use a profiler.




回答3:


Try the profiler in the JDK, visualvm.




回答4:


If it is testing to see how long each method takes to execute, then there are already some good questions relating to this on SO. Check out this one for example.

My preference, especially in a larger project with many methods, would be to use AOP so it doesn't involve changing existing code too much. This answer on the question I linked to above suggests AOP for the same reasons. As he suggests, going in depth in AOP is beyond the scope of this, but it is certainly worth a look. Take a look at this tutorial into how to use spring for method timings.



来源:https://stackoverflow.com/questions/9444349/java-how-can-i-measure-method-call-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!