I'm parsing a file with a few actions, and I want to measure the time that it takes to perform those actions.
What is the best way to do this and print the time?
Update: If you're not opposed to using external libraries and you're on JDK 5+, Google Guava has a Stopwatch that uses System.nanoTime(). It is not associated with absolute system or wall clock time but instead is useful only when calculating elapsed time, but this is exactly what you want.
Otherwise, you can use System.currentTimeMillis() which returns the current system time in milliseconds as a long integer.
long start = System.currentTimeMillis();
// ... perform operations ...
long time = System.currentTimeMillis() - start;
System.out.println("Operation took " + time + "ms");
Timing short-run operations can be very tricky, especially when you run them in a loop to amortize it across multiple runs. You're at the whims of the task scheduler of the operating system and Java's internal thread scheduler.
To mitigate these issues, average the time across multiple runs and move console output operations out of the timing if possible. Just keep in mind that you're not going to get exact numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With