In Java, what is the fastest way to get the system time?
System.currentTimeMillis()
is fastest as per below test case
public class ClassTest
{
@Test
public void testSystemCurrentTime()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < 1_00_000; i++)
{
System.currentTimeMillis();
}
stopwatch.stop();
System.out.println("System.currentTimeMillis(): " + stopwatch);
}
@Test
public void testDateTime()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < 1_00_000; i++)
{
(new Date()).getTime();
}
stopwatch.stop();
System.out.println("(new Date()).getTime(): " + stopwatch);
}
@Test
public void testCalendarTime()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < 1_00_000; i++)
{
Calendar.getInstance().getTimeInMillis();
}
stopwatch.stop();
System.out.println("Calendar.getInstance().getTimeInMillis(): " + stopwatch);
}
@Test
public void testInstantNow()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
for (int i = 0; i < 1_00_000; i++)
{
Instant.now();
}
stopwatch.stop();
System.out.println("Instant.now(): " + stopwatch);
}
}
Output:
(new Date()).getTime(): 36.89 ms
Calendar.getInstance().getTimeInMillis(): 448.0 ms
Instant.now(): 34.13 ms
System.currentTimeMillis(): 10.28 ms
But,
Instant.now()
is fast + simpler and provides other utility as well like Instant.now().getEpochSecond();
,Instant.now().getNano();
, Instant.now().compareTo(otherInstant);
and many more.
System.currentTimeMillis()
"Returns the current time in milliseconds".
Use this to get the actual system time.
System.nanoTime()
.
"The value returned represents nanoseconds since some fixed but arbitrary origin time"
Use this is you're measuring time lapses / events.