I'm trying to get the execution time for an algorithm of a java program. I've looked around at similar questions and tried a few ways to do that, but when I print the time lapse I always get 0.
Instant start = Instant.now();
//Method I want to get the exec time
Instant end = Instant.now();
System.out.println("\nTime lapse: "+Duration.between(start, end));
Prints:
Time lapse: PT0S
As well as:
Date d = new Date();
long t1, t2;
t1 = d.getTime();
//Method I want to get the exec time
t2 = d.getTime();
System.out.println("\nTime lapse: "+(t2-t1));
Outputs:
Time lapse: 0
Meanwhile, getting the exec time in C of the exact same method, gives a fair result:
#include <time.h>
clock_t start, end;
double time;
start = clock();
//Method I want to get the exec time
end = clock();
time = (double) (end-start) / CLOCKS_PER_SEC;
printf("\nTime lapse: %f\n", time);
Outputs:
Time lapse: 0.000004
Why can't I do that in Java?
EDIT
I've tried to use getTimeInMillis() as suggested:
Calendar cal = Calendar.getInstance();
double start = cal.getTimeInMillis();
//Method I want to get the exec time
double end = cal.getTimeInMillis();
System.out.println("\nTime lapse: "+(end - start));
Outputs:
Time lapse: 0.0
FINAL EDIT: Ok so, the program did run in less than a millisecond, that's why I kept getting 0 as a result, and I solved thanks to @Ayo K advice, I used System.nanoTime() to finally get a result.