在Java中,获取系统时间的最快方法是什么?

Ren*_*ani 8 java time calendar

我正在开发一个经常使用系统时间的系统,因为Delayed界面.

什么是从系统中获取时间的紧固方式?

目前我Calendar.getInstance().getTimeInMillis()每次都需要花时间使用,但我不知道是否有更快的方法.

Boz*_*zho 17

System.currentTimeMillis()
"以毫秒为单位返回当前时间".
使用它来获取实际的系统时间.

System.nanoTime().
"返回的值代表纳秒,因为某些固定但任意的原点时间"
使用这是你在测量时间流逝/事件.

  • 请注意,这两种方法具有不同的特性,您应该选择适合您需要的方法. (2认同)

par*_*hah 5

System.currentTimeMillis()根据以下测试用例最快

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

(new Date()).getTime(): 36.89 ms
Calendar.getInstance().getTimeInMillis(): 448.0 ms
Instant.now(): 34.13 ms
System.currentTimeMillis(): 10.28 ms
Run Code Online (Sandbox Code Playgroud)

Instant.now()更快+更简单,并提供其他实用程序,例如Instant.now().getEpochSecond();,,等等。Instant.now().getNano();Instant.now().compareTo(otherInstant);