Nicky
Nicky

Reputation: 97

Measuring the time spent executing the code

Let's say I have the following for loop that I want to time:

for(int i = 0; i < list.size() - 1; i++ ) {     
{
// call other methods, let's say call other 3-4 methods

}

So, if I want to measure how much time that for loop takes to run with an in built Java long time = System.nanoTime(); before and after the for loop, will it also measure the time spent inside the methods that I'm calling?

Or if I don't call other methods and just put all the code inside my for loop, it would take much more time than If I were just calling other methods?

Upvotes: 0

Views: 244

Answers (3)

AxelH
AxelH

Reputation: 14572

Here is a simple example of what I would use to do some basic and not precise test.

We first need some basic methods to start and print the time easily

public class Main {

    static long start;

    static void startTest(){
        start = System.nanoTime();
    }

    static void stopTest(){
        System.out.format("%012.6f ms\n",(System.nanoTime() - start)/1000000.0);
        start = -1;
    }
}

Single Thread

Lets run a test on an empty loop :

startTest();
for(int i = 0; i < Integer.MAX_VALUE; ++i){}
stopTest();

This will wait that the loop end before calling stopTest() and print the time it takes.

Multi-thread

With a different thread, you need to wait that they ends, this is simple and can be don't in multiple ways. Here is one :

startTest();
List<Callable<String>> list = new ArrayList();
for(int i=0;i<5;i++){
    list.add(new Callable() {
        public Object call() throws Exception {
            for(int i = 0; i < Integer.MAX_VALUE/5; ++i){}
            System.out.println("End of Thread");
            return null;
        }
    });
}
ExecutorService es = Executors.newCachedThreadPool();
try {

    es.invokeAll(list);
} catch (InterruptedException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} finally {
    stopTest();
    es.shutdown();
}

With this Executors, we can invoke all Callable at the same time an wait for them to end.

Upvotes: 0

Jay
Jay

Reputation: 1119

System.nanoTime() returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.

From the Java's Documentation:

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

Calculating time by using System.nanoTime() values would calculate the full time taken to execute that loop. This would include the execution time of the methods inside the loop (if they are there).

However, if it happens that you start threads inside the loop which have their own execution time, the time elapsed from point 1 to point 2 would only be the time taken to start the threads, not their execution time.


I have found a good way to understand this thing. Just write a simple code:

long t1 = System.nanoTime();
long t2 = System.nanoTime();
System.out.println((t2 - t1) / 1000000);
  1. Pull this in a debugger and see what happens when you don't apply any breakpoints.

  2. Now apply a breakpoint at line #2 and wait for some time there before resuming the execution.

You could see the difference.


Reference Link

Upvotes: 0

bashrc
bashrc

Reputation: 4835

The timer just counts the difference between the time it starts and it ends. It has no knowledge of what happened between the start and the end. So it doesn't matter if you dump all your code inside the for loop, or call those methods directly instead of inlining them.

However this would not give you the time taken by each individual function. You may want to look at Java profilers to get results in a more systematic way.

Upvotes: 1

Related Questions