Same function different runtime?! Why is the time measured not the same when adding code elsewhere? Java, Sorting algorithm time measurement, nanotime

40 views Asked by At
Function1 num1 = new Function1();
//Function2 num2 = new Function2();


ArrayList<Integer> nonSortedList = new ArrayList<>();
for (int i=1; i<10000000; i++) nonSortedList.add(i);
Collections.shuffle(nonSortedList);
ArrayList<Integer> nonSortedList2 = new ArrayList<>(nonSortedList);
//ArrayList<Integer> nonSortedList3 = new ArrayList<>(nonSortedList2);



System.out.println();
System.out.println();

long start = System.nanoTime();
Collections.sort(nonSortedList);
System.out.println("function1= "+((System.nanoTime()-start)/1000000000.0));

start = System.nanoTime();
num.sort(nonSortedList2);
System.out.println("function2= "+((System.nanoTime()-start)/1000000000.0));

/*
start = System.nanoTime();
num2.sort(nonSortedList3);
System.out.println("function3= "+((System.nanoTime()-start)/1000000000.0));
*/

Output without commented lines:
function1= 6-7 seconds
function2= 2-3 seconds

Output with commented lines included:
function1= 3.8144072
function2= 5.8931552
function3= 4.2656519

What I expected to happen is the runtime of the sort algorithm of Collection.sort() and the Function1 sort algorithm to remain the same after adding the Funtion2 algorithm measurement code,

Why does the code added elsewhere make Collections.sort() faster and the second sorting function slower. How is this possible?

Why is the speed changing with new code added when the function being measured between System.nanotime() calls is still the same?

Note that i have also tried Instant.now(), the problem has something to do with the syntax of my measuring code... definitely not the functions

0

There are 0 answers