-2

I have an interface IMath having add, subtract methods

public interface IMath {

    long add(int x, int y);
    long sub(int x, int y);
}

Now a class Math implementing this is having the body for these methods.

public class Math implements IMath {
    @Override
    public long add(int x, int y) {
        return x + y;
    }

    @Override
    public long sub(int x, int y) {
        return x - y;
    }
}

I want the execution time for each method without using AOP, Reflection and no changes should be there in the method code.

Please suggest various ways to do this

3 Answers3

0

To calculate execution time without using AOP, Reflection and no changes in the method code, This might help you.

Praveen
  • 432
  • 1
  • 6
  • 14
0

You have ruled out all practical options apart from running your code using a profiler that can instrument the code and measure elapsed time for the calls.

However, I would note that profiling is only going to be viable if this code is used in an (exist) application that repeatedly calls the methods. Even then, since the methods are so short, getting reliable measurements will be difficult.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

When you don't need to change code and want to add additional behavior simple use decorator pattern and decorate your existing code:

public class MathMeasure implements IMath {
    private final IMath math;
    private long lastMethodTime;

    public MathMeasure(IMath math) { this.math = math; }


    @Override
    public long add(int x, int y) {
        long result;
        long start = System.currentTimeMillis();
        result = math.add(x, y);
        long end = System.currentTimeMillis();
        lastMethodTime = end - start;
        return result;
    }

    @Override
    public long sub(int x, int y) {
         //same code here like in previous method
    }

    public long lastMethodInvokationTime() { return lastMethodTime; }

}

This is basic idea of how it works, you may need to add more complex time execution logging. Let's see what we done here, with decorator pattern you create something that implements IMath interface and put it inside decorator after that feel free to pass this bunch to clients (another part of application) because decorator also have IMath interface and clients don't see additional methods but you may collect data after clients IMath usage.

fxrbfg
  • 1,756
  • 1
  • 11
  • 17