Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I time a method's execution in Java?

  1. How do I get a method's execution time?
  2. Is there a Timer utility class for things like timing how long a task takes, etc?

Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.

like image 953
Ogre Psalm33 Avatar asked Oct 07 '08 20:10

Ogre Psalm33


People also ask

How do you record time in Java?

Using Instant. Instant class can be used to record event time-stamps in the application. It has now() method that obtains the current instant from the system clock. We can convert this instant to the total number of milliseconds using toEpochMilli() method. Please note that Instant.

How do you calculate Execution time?

The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.

Is there a time function in Java?

The time functions can be accessed from the java. util. Date class. This represents an instance of time with millisecond precision.


Video Answer


1 Answers

There is always the old-fashioned way:

long startTime = System.nanoTime(); methodToTime(); long endTime = System.nanoTime();  long duration = (endTime - startTime);  //divide by 1000000 to get milliseconds. 
like image 73
Diastrophism Avatar answered Sep 27 '22 21:09

Diastrophism