-2

I am supposed to measure the running time of certain tree operations. for some reason when printing x or y i get the whole number but when trying to print (y-x) i get an unusually small number! i get 2000 instead of 200,000.

long y=0;
long x=0;

for(int j=0 ; j < 1000 ; j++)
{
        if(j%100==0) System.out.println(y-x);   
        x = System.nanoTime();
        myTree.put(n, 0);
        y = System.nanoTime();
}
SimplyPanda
  • 725
  • 7
  • 16
Ethan
  • 261
  • 5
  • 16
  • What are the values for x and y in this code? – Maurício Linhares Dec 10 '13 at 16:26
  • 4
    The subtraction result denotes the difference. Yes it can be small and it is just saying it needed `2000 nanoseconds` to put the (key, value)pair to the map – Sage Dec 10 '13 at 16:26
  • On the first call, you'll just print 0. After that, you realize you're timing a single invocation of put, not the cumulative call time, right? – David Ehrmann Dec 10 '13 at 16:29
  • 1
    @Hilikus - 2000 ns is 2 µs, not 2 ms. – dcsohl Dec 10 '13 at 16:32
  • when printing x and y separately then substracting manually i get a result atleast 100 times higher, but when using java to print the substraction i get a tiny result... i want to make sure i haven't missed a bug in here that ruins my calculation – Ethan Dec 10 '13 at 16:33
  • @Ethan, Nope that can not be. I won't believe you. If you assign `System.nanoTime()` to a variable `x` then in an immediate second statement you write `System.nanoTime() - x`, then yes you will see that the maximum elapsed time it can show `7xxx` or a little higher. This is at least true for my Dual Core machine. You can see a deviation but not really notable. – Sage Dec 10 '13 at 16:40
  • I think i realized my error, when stating the system.nanotime() command within the println("") method it added all that extra time therefor the huge difference from first substracting and only then printing the result, thanks for the help :) – Ethan Dec 10 '13 at 16:48

2 Answers2

0

From the documentation :

public static long nanoTime()

Returns the current value of the most precise available system timer, in nanoseconds.

So actually the time seems ok for such an elementary operation like put.

But beware of the JVM warmup phase (see How to avoid JVM warmup) which alters results. Actually the first values of x and y needs to be discarded (This might be the reason of why you see such high values for x and y at first and then low results). If you want accurate results, either try to do some computation before benchmarking the put function or use some tools such as Caliper which eases the work.

Community
  • 1
  • 1
abronan
  • 3,309
  • 4
  • 29
  • 38
-1

There's issue with System.nanoTimes.

You can refer below link:-

Precision vs. accuracy of System.nanoTime()

Community
  • 1
  • 1
Encyclopedia
  • 134
  • 1
  • 9