5

When attempting to investigate the runtime of various tasks using System.nanoTime(), the value, when the input data-set is large enough, turns negative.

The example code used:

long start = System.nanoTime();
run();
long stop = System.nanoTime();

int diff = (int) (stop-start);
System.out.println(data_size+", "+diff);

The output, when invoking run() on an increasingly big data-set, looks like this:

1, 80000
10, 4310000
50, 48077000
100, 171363000
250, 1061924000
500, 14018704
750, 998074408
1000, -41025184
1500, -81710664
2000, -273795736
2500, 768997600
3000, -39161248

Does this make sense to anyone?

krystah
  • 3,587
  • 2
  • 25
  • 43
  • possible duplicate of [Why I get a negative elapsed time using System.nanoTime()?](http://stackoverflow.com/questions/7866206/why-i-get-a-negative-elapsed-time-using-system-nanotime) – turbo Jan 24 '14 at 17:52
  • 2
    @turbo This is not a duplicate of that question; this is caused by casting to the difference to `int`. – rgettman Jan 24 '14 at 17:59

3 Answers3

13

You casting the difference between two long to an int. Likely, your long difference is longer than Integer.MAX_VALUE (about 2 billion) and the cast to int takes the last 32 bits, yielding a negative number. Besides, 2 billion nanoseconds is only 2 seconds, so any time longer that will overflow an int.

Keep the difference as a long.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

I would guess this is an integer overflow issue. int range is in:

Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648

Try using long to store diff value instead:

long diff = stop - start;
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

In Java, an the maximum number for an int (represented by 32 bits) is 2^31 or 2,147,483,647. What is happening is that when the difference is greater than this number, it can't be represented by an int and overflows (ran out of bits)

Noxoin
  • 1
  • 1
  • 1