I have a requirement to fix the execution time of some code in iterations. I decided to use Map<Integer,Long> to write this data, where the Integer (key) is the iteration number, and Long (value) is the time it takes for the iteration in milliseconds .
I wrote java code to calculate the time spent on each iteration. I want to make sure that the time taken for all iterations is zero before calling the actual code. Surprisingly, the code below behaves differently for each execution.
Sometimes I get the desired result (zero milliseconds for all iterations), but sometimes I get positive and even negative values for some random iterations.
I tried replacing System.currentTimeMillis(); the code below:
new java.util.Date().getTime();
System.nanoTime();
org.apache.commons.lang.time.StopWatch
but still no luck.
Any suggestions why some iterations take extra time and how to fix it?
package com.stackoverflow.programmer; import java.util.HashMap; import java.util.Map; public class TestTimeConsumption { public static void main(String[] args) { Integer totalIterations = 100000; Integer nonZeroMilliSecondsCounter = 0; Map<Integer, Long> timeTakenMap = new HashMap<>(); for (Integer iteration = 1; iteration <= totalIterations; iteration++) { timeTakenMap.put(iteration, getTimeConsumed(iteration)); if (timeTakenMap.get(iteration) != 0) { nonZeroMilliSecondsCounter++; System.out.format("Iteration %6d has taken %d millisecond(s).\n", iteration, timeTakenMap.get(iteration)); } } System.out.format("Total non zero entries : %d", nonZeroMilliSecondsCounter); } private static Long getTimeConsumed(Integer iteration) { long startTime = System.currentTimeMillis();
Here, the sample is derived from 5 different executions of the same code:
Execution # 1 (NOT OK)
Iteration 42970 has taken 1 millisecond(s). Total non zero entries : 1
Execution # 2 (OK)
Total non zero entries : 0
Execution # 3 (OK)
Total non zero entries : 0
Execution # 4 (NOT OK)
Iteration 65769 has taken -1 millisecond(s). Total non zero entries : 1
Execution # 5 (NOT OK)
Iteration 424 has taken 1 millisecond(s). Iteration 33053 has taken 1 millisecond(s). Iteration 76755 has taken -1 millisecond(s). Total non zero entries : 3
I am looking for a Java-based solution that ensures that all iterations consume zero milliseconds in sequence. I prefer to do this using pure Java code without using a profiler.
Note. I was also able to accomplish this using C code.