开发者

Timer code does not work

Timer Java code does not work

public interface IncDec
{
 void increment();
 void decrement();
}
public class MyIncDec implements IncDec
{
 private int x;
 public MyIncDec(int x) {
  this.x = x;
}
 public void increment() {
  this.x++;
 }
 public void decrement() {
  this.x--;
 }
}

Part 1: Implement a class which can be used to measure how long each invocation of the increment and decrement method takes (in milliseconds) and prints out this information. The class should fit in more or less transparently with existing clients of the IncDec interface.

My Solution:

public class Test{
public static void main(String[] args){
MyIncDec mid = new MyIncDec(4);
long l1;
long l2;

l1 = Calendar.getInstance().getTimeInMillis();
mid.increment();
l2 = Calendar.getInstance().getTimeInMillis();
System.out.println(l2-l1);
}
}

My Solution gives me the time diff as 0. When I d开发者_运维知识库isplay the long values before n after calling 'increment', They are the same. Why so?

Suppose if I had to something similar (timing of method calls) for many places in an application. One idea would be to write a separate timer class for all different methods. Does anyone have another optimized idea to get timing more conveniently?


First of all, you are 0 as time difference, because it's probably taking less than 1 millisecond to run. Try adding a Thread.sleep(50) in your increment method to see if something changes.

 public void increment() {
  try { Thread.sleep(50); } catch (InterruptedException e) { }
  this.x++;
 }

Second, your homework probably wants you to use the IncDec interface in the class computing your time. So take that into consideration. Do learn what interfaces are, what are they used for and, more importantly, how they are used.

Good luck!


I think your homework is suggesting you make use of the Proxy Pattern

I'm not going to give you the full solution, but here's a hint:

public class MyIncDecProxy implements IncDec{

    MyIncDec incDec;

    public MyIncDecProxy(int x){
        //Initialise incDec
    }

    public void increment() {
        // Wrap the method of incDec implementing your timer
    }

    public void decrement() {
        //ditto
    }

}

You would then use the MyIncDecProxy class instead of MyIncDec


  1. I believe that your code works. You have to thank the modern computers: they are very fast. If you wish to see difference write loop 0..1000000 instead of single call of mid.increment(). Alternatively mesure time in nanoseconds.
  2. If it is not an exercise but real task use java profiler. There are a lot free and commercial profilers. This tool will provide you the best information.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜