I currently have the following code:
public static int currentTimeMillis()
{
long millisLong = System.currentTimeMillis();
while ( millisLong > Integer.MAX_VALUE )
{
millisLong -= Integer.MAX_VALUE;
}
return (int)millisLong;
}
which returns the current time in an int format (not exactly, but it can be used for time differences). For very good reasons, I can’t use long.
Yes, I am just interested in the difference between two calls, and this approach works well. But it just looks wrong. I know that. And inefficient. I know. So my questions is, how can I improve it?
I need a function that returns an int such that:
int x1 = currentTimeMillis(); //my function
long y1 = System.currentTimeMillis();
.....
int x2 = currentTimeMillis();
long y2 = System.currentTimeMillis();
// here, x2 - x1 must be equal to y2 - y1
EDIT:
FYI, I want to do this for benchmarking. I’m running tests on multiple threads in parallel, the stop event is triggered by an external component. I’m also serializing the data in a way that only supports int, and the object I’m serializing can not have long members.
Your function does essentially the same as:
The above is probably what you’re looking for. The modulus operator
%returns the remainder of the division. I would only wrap it in another class which hides this away. It’s namely confusing to have “current time in millis” as an int with the wrong value. Something like:with
This is also much better in order to prevent problems when the start time is less than
Integer.MAX_VALUEand the end time is larger thanInteger.MAX_VALUEwhich thus overflows back toInteger.MIN_VALUEand continues from there.