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?
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.
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
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With