Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing an action

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?

like image 648
Darth Blue Ray Avatar asked Feb 23 '26 17:02

Darth Blue Ray


1 Answers

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.

like image 152
David Harkness Avatar answered Feb 25 '26 06:02

David Harkness



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!