Subtraction of System.currentTimeMillis() yielding zero

I am trying to keep track of time in my program using System.currentTimeMillis() However, when I try to subtract the start time from the end time the result is zero when I know it should not be. I think it may have to do with the declared datatype or type-casting that may be necessary. How can I fix it to subtract properly and convert the result to seconds?

See code:

long start=System.currentTimeMillis();
//some code executes....
    long end=System.currentTimeMillis();
    long result=end-start;
double seconds= TimeUnit.MILLISECONDS.toSeconds(result);

Answer

No, your code is fine. Most likely a millisecond just isn’t elapsing. Try using System.nanoTime() instead.

EDIT: Actually, there is an issue with the code. Per the TimeUnit.convert docs, “Conversions from finer to coarser granularities truncate, so lose precision”, so if result is less than 1000, it will be 0.

If you want fractional seconds, just do:

double seconds = result / 1000.0;

nanoTime could still be useful, but it might not be an issue if the code takes long enough.

Leave a Reply

Your email address will not be published. Required fields are marked *