javajvmruntime

Will JVM optimise this mathmatical operation?


long time= (getTime()/60000L) * 60000L

The getTime() will return unix time in millis. I am exploiting division with longs to write off seconds and millis. The result must also be in unix time format (resolution upto millis)

I am wondering if JVM would optimise the above code to

long time= getTime()

But this will alter the result.

Or is there a better, cleaner way? (Can't change getTime's return type, which is also long)

Thanks in advance for any help.


Solution

  • Summarizing the comments into a Community Wiki answer:

    It would be a major bug if the JVM "optimized" that code in the way you describe. Intentionally using truncating division and other similar operations is common, optimizing them away would be breaking the semantics of the code. So your existing code should be just fine.


    You asked about other ways. There are at least a couple.

    You could do a remainder (% 60000L) and subtraction rather than division and multiplication, although that still leaves a "magic number" (60000L) in the code you'd need to explain with a comment or similar:

    long time = getTime();
    time = time - time % 60000L;
    

    Or you could make the time semantics obvious by using the java.time.Instant class:

    long time = Instant.ofEpochMilli(getTime())
        .truncatedTo(ChronoUnit.MINUTES)
        .toEpochMilli();
    

    (You only need the .toEpochMilli() on the end if you need your result to be a Unix milliseconds time value again as it is in your current code; otherwise, it would be an Instant instance).

    But again, while you can do either of those (and probably others), you don't have to change your code if you don't want to.