Timer code not working

Timer Java code not working

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: Introduce a class that can be used to measure how long each invocation of the increment and decrement method (in milliseconds) takes and prints this information. The class should be more or less transparent with existing IncDec interface clients.

My decision:

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 a time difference of 0. When I output long values ​​to n after calling increment, they are the same. Why is that?

Suppose I had something similar (method call time) for many places in the application. One idea would be to write a separate timer class for all the different methods. Does anyone have another optimized idea to get a convenient time?

+3
3

, 0 , , , 1 . Thread.sleep(50) increment, , - .

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

-, , , , IncDec , . . , , , , , .

!

+1

, , -

, :

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
    }

}

MyIncDecProxy MyIncDec

+1
  • I believe your code works. You have to thank modern computers: they are very fast. If you want to see the difference, write a cycle of 0..1000000 instead of a single call mid.increment(). Alternatively, the decay time in nanoseconds.
  • If this is not an exercise, but a real task, use the java profiler. There are many free and commercial profilers. This tool will provide you the best information.
-1
source

Source: https://habr.com/ru/post/1779831/


All Articles