Salman Raza
Salman Raza

Reputation: 1715

How to get the microseconds from a Date?

I am trying to get microseconds from a Date, but I can't.

Date date = new Date()

Upvotes: 3

Views: 15342

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533472

What I do is find the difference between the currentTimeMillis and the nanoTime() at regular intervals (as this drifts quite a bit) and use nanoTime() + OFFSET for a currentTimeNS. (More specificity I use the RDTSC machine code instruction, which comes with even more quibbles ;)

However, its is less accurate than currenTimeMillis() over time which itself can drifts by many milli-seconds in an hour.

It only really useful if you understand its limitations.

Upvotes: 2

Turix
Turix

Reputation: 178

To measure time in microseconds you need to use the System.nanoTime() function which will return a time in microseconds based on the most accurate clock available to your system.

To the user this acts in pretty much the same way as System.currentTimeMilis() does for milliseconds, you simply define your start and end times and then negate the difference to find out how long an action took. For example:

long startTime = System.nanoTime();
//Do some kind of processing; 
//loop, IO, whatever you want to measure
long endTime = System.nanoTime();
long elapsedTime = endTime - startTime;

The last bit can be shorted, I've left it verbose for simplicity:

long elapsedTime = System.nanoTime() - startTime;

This should not be used to measure real time as it has very little meaning or guarantee that it is even comparable to it. All of the above information is available from the Java API documentation for System.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499880

No, Date only stores values to millisecond accuracy. If you want microsecond accuracy, you might want to look at JSR-310, or java.sql.Timestamp as a bit of a hack - but don't expect any of the built-in classes such as Calendar and DateFormat to handle anything beyond milliseconds.

If you're trying to perform timing (e.g. for benchmarking) you should use System.nanoTime, but that should only be used for stopwatch-like use cases - it doesn't give you the "current wallclock time" in a meaningful way.

Upvotes: 16

Related Questions