Question

class testx
{
  public testx()
  {
    long startTime = System.nanoTime();
    System.out.println((System.nanoTime() - startTime));
  }

  public static void main(String args[])
  {
      new testx();
      new testx();
      new testx();
  }
}

I always get results similar to this 7806 660 517. Why the first call takes 10 times more time than other ones?

Was it helpful?

Solution

Because the JVM loads a bunch o' classes for the first time at that point. Once that first System.nanoTime() returns, you have already loaded System.class and testx.class, but once System.out.println comes into the picture, I suspect a lot of I/O classes get loaded up, and that takes some time.

In any event, this is not a good benchmarking technique; you should really be warming up the JIT by running something for ~10000 iterations before you start measuring it. Alternately (and preferably), use a pre-built benchmarking tool like Caliper.

OTHER TIPS

It is definitely as Louis Wasserman, It takes longer on its first round as it has to load all the necessary System classes, you can get around this by calling a blank println() before creating new instances of the class, because look what happens when we do this:

public class testx
{
  public testx()
  {
    long startTime = System.nanoTime();
    System.out.println((System.nanoTime() - startTime));
  }

  public static void main(String args[])
  {
    //loads all System.* classes before calling constructor to decrease time it takes
    System.out.println();
      new testx();
      new testx();
      new testx();
  }
}

output:

405 0 405

where as your initial code outputted:

7293 0 405

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top