0

Since I wanted to check several methods (foo(int)) for efficiency and compare them to the overall runtime I ended up writing something similar to:

void testNanoTime(){
    long methodDuration = 0;
    long testStart = System.nanoTime();
    for(int i= 0; i< 300; i++){

        long startJob = System.nanoTime();
        foo(i);  //checking how foo does with certain data.
        methodDuration+= System.nanoTime()-startJob;

        bar();
    }
    System.out.println("MethodDuration: "+methodDuration);
    System.out.println("TestDuration:   "+(System.nanoTime()-testStart));
}

foo(int) sometimes needs several minutes up to half an hour (but not in sum 293 years!) per call. The issue is now, that sometimes the TestDuration (the whole time the method takes) is smaller than the methodDuration, which seems impossible to me. Hence two questions:

  • To which amount are my older tests comparing methodDurations still valid?
  • What should I use for further testing of performance without danger of getting invalid timeStamps? Would be System.currentTimeMillis() safe to go or has it the same issues?

Currently the testing takes place at a linux system. I already found some older questions and answers regarding this issue here (e.g. Is System.nanoTime() completely useless?), but some state it is a Windows problem and other answers remain unclear as they mention, they might be outdated (and they are even several years old). Even most answers contradict each other!

Community
  • 1
  • 1
ctst
  • 1,610
  • 1
  • 13
  • 28
  • 1
    I am unable to reproduce this problem using [Ideone](http://ideone.com/5NnTxw). – bcsb1001 Mar 18 '16 at 13:39
  • @RC @Ideone The problem occurred with larger calculations in the methods `foo` and `bar` outsourced into other classes. Some of the older questions/answers state, it is a problem with multicores, while some state the problem got fixed, others claim it still persists (look at the link of RC). It is in such a sense not a duplicate, since the most upvoted and accepted answer even states it is most surely outdated! – ctst Mar 18 '16 at 13:42

1 Answers1

1

Java profiling is rather complex based on how the JVM works.

Here are some resources to help you get started

For specifics on nano time and how it works, read Nano Time Completely Useless

Edit: OP edited post to mention, "Nano Time Completely Useless" but keeping it in the answer since IMHO it's still relevant.

Community
  • 1
  • 1
wiredniko
  • 2,491
  • 3
  • 19
  • 37
  • The problem in my case is, the considered methods use queries outside of java (otherwise your solutions seems fine). Also the bottleneck is known, right now I am just comparing possible solutions, when stumbled upon this issue. – ctst Mar 18 '16 at 13:58