So, I am trying to measure the execution time of some sorting methods.
Here is my code:
public static void main(String[] args)
{
...
MeasureExecutionTime(new Runnable() { public void run() { insertionSort(C); } }, "insertionSort()");
}
=====================
private static void MeasureExecutionTime(Runnable r, String s)
{
startTime = System.nanoTime();
try
{
r.run();
}
finally
{
endTime = System.nanoTime();
}
elapsedTime = endTime - startTime;
System.out.println(s + " takes " + elapsedTime + " nano-seconds which is " + formatTime(elapsedTime));
}
=====================
public static String formatTime(long nanoSeconds)
{
long hours, minutes, remainder, totalSecondsNoFraction;
double totalSeconds, seconds;
totalSeconds = (double) nanoSeconds / 1000000000.0;
String s = Double.toString(totalSeconds);
String [] arr = s.split("\\.");
totalSecondsNoFraction = Integer.parseInt(arr[0]);
hours = totalSecondsNoFraction / 3600;
remainder = totalSecondsNoFraction % 3600;
minutes = remainder / 60;
seconds = remainder % 60;
seconds = Double.parseDouble(Long.toString((long)seconds) + Double.parseDouble("." + arr[1]));
StringBuilder result = new StringBuilder(".");
String sep = "", nextSep = " and ";
if(seconds > 0)
{
if(seconds > 1) result.insert(0, " seconds").insert(0, seconds);
else result.insert(0, " second").insert(0, seconds);
sep = nextSep;
nextSep = ", ";
}
if(minutes > 0)
{
if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
sep = nextSep;
nextSep = ", ";
}
if(hours > 0)
{
if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
else result.insert(0, sep).insert(0, " hour").insert(0, hours);
}
return result.toString();
}
My problem is:
After run this program, and I enter int[1000000] as an input, it executes insertionSort() in about 12-13 minutes and then returns:
insertionSort() takes 767186856920 nano-seconds which is 12 minutes and 470.18685692 seconds.
why it gives 470 seconds? what is wrong in my code?
=========================
EDIT:
After replacing seconds = Double.parseDouble(Long.toString((long)seconds) + Double.parseDouble("." + arr[1])); with seconds = seconds + Double.parseDouble("." + arr[1]);, the previous issue is gone, but another issue showed up:
insertionSort() takes 22864 nano-seconds which is 2.000002864 seconds.
It should be 0.000022864 seconds.
=========================
EDIT2:
I might discover the error. when nanoSeconds is large, arr[1] will be ok but when nanoSeconds is small, arr[1] will convert to exponential form, i.e 14931 nano-seconds => 4.931E-6 seconds.. How can I solve this issue?
==========================
EDIT3:
Ok, I found the solution:
if(arr[1].contains("E")) seconds = Double.parseDouble("." + arr[1]);
else seconds += Double.parseDouble("." + arr[1]);
The problem is here:
Say
secondsis12entering this line andarr[1]is"456". ThenWhy not just do: