因爲Delayed
接口,我正在開發一個經常使用系統時間的系統。在Java中,獲得系統時間的最快方法是什麼?
從系統中獲取時間的方式是什麼?
當前我每次需要時間都使用Calendar.getInstance().getTimeInMillis()
,但我不知道是否有更快的方法。
因爲Delayed
接口,我正在開發一個經常使用系統時間的系統。在Java中,獲得系統時間的最快方法是什麼?
從系統中獲取時間的方式是什麼?
當前我每次需要時間都使用Calendar.getInstance().getTimeInMillis()
,但我不知道是否有更快的方法。
System.currentTimeMillis()
「返回以毫秒爲單位的當前時間」。
使用它來獲取實際的系統時間。
System.nanoTime()
。
「返回的值表示自某個固定但任意原點時間以來的納秒」
使用這是您正在測量時間失效/事件。
請注意,這兩種方法有不同的特點,您應該選擇適合您需要的方法。 –
據我所知,DelayQueue使用TimeUnit.NANOSECONDS來計算時間,所以'System.nanoTime()'在這種情況下更適合避免必須在getDelay()'方法中轉換爲單位。 –
你可以在那裏使用任何單位,所以可以工作。 nanoTime更精確 – Bozho
System.currentTimeMillis
是簡單的答案
long timeMilliSec = System.currentTimeMillis();
簡而言之,System.currentTimeMillis()
更快。
@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);
}
我跑上面的測試案例,我發現以下結果:
System.currentTimeMillis(): 5.208 ms (new Date()).getTime(): 19.57 ms Calendar.getInstance().getTimeInMillis(): 148.2 ms
System.currentTimeMillis(): 4.685 ms (new Date()).getTime(): 11.53 ms Calendar.getInstance().getTimeInMillis(): 122.6 ms
System.currentTimeMillis(): 4.734 ms (new Date()).getTime(): 11.66 ms Calendar.getInstance().getTimeInMillis(): 131.5 ms
System.currentTimeMillis(): 4.018 ms (new Date()).getTime(): 19.33 ms Calendar.getInstance().getTimeInMillis(): 127.6 ms
System.currentTimeMillis(): 5.474 ms (new Date()).getTime(): 16.74 ms Calendar.getInstance().getTimeInMillis(): 113.6 ms
System.currentTimeMillis(): 3.871 ms (new Date()).getTime(): 14.46 ms Calendar.getInstance().getTimeInMillis(): 120.5 ms
System.currentTimeMillis(): 8.223 ms (new Date()).getTime(): 11.65 ms Calendar.getInstance().getTimeInMillis(): 173.8 ms
System.currentTimeMillis(): 4.611 ms (new Date()).getTime(): 9.978 ms Calendar.getInstance().getTimeInMillis(): 117.9 ms
System.currentTimeMillis(): 3.794 ms (new Date()).getTime(): 11.33 ms Calendar.getInstance().getTimeInMillis(): 89.79 ms
System.currentTimeMillis(): 4.298 ms (new Date()).getTime(): 12.37 ms Calendar.getInstance().getTimeInMillis(): 123.8 ms
我希望,這將幫助你。
你在哪裏使用DelayQueue的時間毫秒? – Bozho
我不清楚,我只用在'getDelay()'方法中實現Delayed接口的類中。 –
@Renato,Calendar.getInstance()和新的Date()都使用System.currentTimeMillis(),但Calendar是目前最慢的。 –