javatimelong-integerapache-commons-lang3

Timing method duration: always showing zero seconds?


I am trying to time how long a method takes within my application, the issue is that the timing is always showing 0 seconds. What is wrong with my code below?

long currentTimeInMilis = System.currentTimeMillis() % 1000;

    public ClassName() {

        public void timeMethod() {

                long startOfmethod= currentTimeInMilis;

                methodToTime();

                long endOfMethod= currentTimeInMilis;

                long totalTime = endOfMethod= - startOfmethod;

                LOGGER.info("[Method Took: {}", DurationFormatUtils.formatDuration(totalTime, "H:mm:ss", true) + "]\n");                                            
             }
    }

The issue is that I'm getting this output every time, eventhough I know it is taking more than zero seconds :

Method took: 0:0:0:

Solution

  • You're using the same currentTimeInMilis variable before and after. It's not like something magically changed it in the meantime (well, unless methodToTime does, since you've made it a field rather than a local variable). You have to actually call System.currentTimeMillis() again after the method is complete in order to have a value you can compare with the value from before the method was called.

    E.g., get rid of the currentTimeInMilis field entirely, and see *** below:

    public ClassName() {
    
        public void timeMethod() {
    
            long startOfmethod = System.currentTimeMillis(); // ***
    
            methodToTime();
    
            long endOfMethod = System.currentTimeMillis();   // ***
    
            long totalTime = endOfMethod = -startOfmethod;
    
            LOGGER.info("[Method Took: {}", DurationFormatUtils.formatDuration(totalTime, "H:mm:ss", true) + "]\n");
        }
    }
    

    Note that I've removed the % 1000 as well; it doesn't make sense to only remember the milliseconds part of the value.

    However, note that this is only valid for a very, very rough indication (you've said the method takes two minutes). For proper benchmarking, see How do I write a correct micro-benchmark in Java?