Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current milliseconds, from long to int

Tags:

java

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.

like image 822
Luchian Grigore Avatar asked Nov 23 '11 15:11

Luchian Grigore


People also ask

What does system currentTimeMillis () return UTC?

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.

How Fast Is system currentTimeMillis?

System. currentTimeMillis() takes about 29 nanoseconds per call while System. nanoTime() takes about 25 nanoseconds.

What does currentTimeMillis return?

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.


1 Answers

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);
}
like image 191
bezmax Avatar answered Oct 10 '22 21:10

bezmax