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.
json"(February 26, 2019 12:00:00 AM) and that need to be accessed from android app once device's System. currentTimeMillis() returns exact time.
System. currentTimeMillis() takes about 29 nanoseconds per call while System. nanoTime() takes about 25 nanoseconds.
currentTimeMillis. Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
Instead of finding a modulus, a much faster solution would be a simple bitwise mask operation:
public static int currentTimeMillis() {
return (int) (System.currentTimeMillis() & 0x00000000FFFFFFFFL);
}
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