Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the time it takes a function to complete in Java?

Tags:

java

profiling

People also ask

How do you count the number of times a function is called in Java?

To count how many times a function has been called, declare a count variable outside of the function, setting it to 0 . Inside of the body of the function reassign the variable incrementing it by 1 . The count variable will store the number of function invocations.


long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;

Here is how can compute the elapsed time.

// Get current time
long start = System.currentTimeMillis();

// Do something ...

// Get elapsed time in milliseconds
long elapsedTimeMillis = System.currentTimeMillis()-start;

// Get elapsed time in seconds
float elapsedTimeSec = elapsedTimeMillis/1000F;

// Get elapsed time in minutes
float elapsedTimeMin = elapsedTimeMillis/(60*1000F);

// Get elapsed time in hours
float elapsedTimeHour = elapsedTimeMillis/(60*60*1000F);

// Get elapsed time in days
float elapsedTimeDay = elapsedTimeMillis/(24*60*60*1000F);

If you are using Guava, consider using the Stopwatch, e.g.:

final Stopwatch sw = Stopwatch.createStarted();
methodToBeTimed();
final long elapsedMillis = sw.elapsed(TimeUnit.MILLISECONDS);

Use a profiler.


The profiler is the right answer if you have more than one function.

Another problem that I see with all the suggestions given so far is that they work fine for a single function, but your code will be littered with timing stuff that you can't turn off.

If you know how to do aspect oriented programming, it's a good way to keep the timing code in one place and apply it declaratively. If you use something like Log4J to output the values, you'll have the option of turning it off or on. It's a poor man's profiler.

Have a look at AspectJ or Spring's AOP.