I wouldn't use neither Date
nor LocalDateTime
for measuring short intervals of time. The main reason for this in written in your question, there is a considerable overhead for object creation (check out LocalDateTime source code). Also keep in mind that the JVM need some time to warm up (let JVM optimizations kick in and do its magic).
While you shouldn't benchmark like this (there are lot of good benchmark tools for Java), a good low level alternative is System.nanoTime()
. StopWatch
classes might also come in handy (like Guava, Commons Lang and Spring implementations).
Finally, remember that Thread.sleep is itself subject to precision problems.
// Run several times to *warm up*
for (int i = 0; i < 100; i++) {
double init = System.nanoTime();
Thread.sleep(1);
long end = System.nanoTime();
System.out.printf("Elapsed time: %.2f milliseconds\n", (end - init) * 1e-6);
}