Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.nanoTime() turns negative

Tags:

java

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?

like image 518
krystah Avatar asked Jan 24 '14 17:01

krystah


People also ask

What is system nanotime in Java?

System.nanoTime () returns the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds. The value returned by nanoTime () is the difference, measured in nanoseconds, between the current time and midnight, January 1, 1970 UTC.

What is the value returned by nanotime ()?

The value returned by nanoTime () is the difference, measured in nanoseconds, between the current time and midnight, January 1, 1970 UTC. The syntax of nanoTime () function is

Is nanotime always efficient on the CPU?

But is it always efficient on the CPU to use nanoTime? Let us look at pros and cons of using both the methods: public static long currentTimeMillis () // Returns the current time in milliseconds. It is thread safe. Thread safety means that if this method is called between two or more different threads, it will not return erroneous results.

What is the syntax of nanotime () function in C++?

The syntax of nanoTime () function is The function returns long value. In this example, we will get the current time in the resolution of nanoseconds using System.nanoTime () method.


1 Answers

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.

like image 154
rgettman Avatar answered Oct 01 '22 15:10

rgettman