簡體   English   中英

什么更快? System.currentTimeMillis()或Date()。getTime()?

[英]What is faster? System.currentTimeMillis() or Date().getTime()?

什么是更快的方法?

System.currentTimeMillis() 

要么

new Date().getTime()?

知道經過的時間有更快的解決方案嗎?

如果你這樣做

new Date()

它叫

/**
 * Allocates a <code>Date</code> object and initializes it so that
 * it represents the time at which it was allocated, measured to the
 * nearest millisecond.
 *
 * @see     java.lang.System#currentTimeMillis()
 */
public Date() {
    this(System.currentTimeMillis());
}

所以它調用System.currentTimeMillis()並創建一個立即丟棄的對象。

如果你很幸運,逃逸分析將刪除冗余對象,性能將大致相同。

但是,我不認為Escape Analysis會啟動並且只是打電話

long start = System.currentTimeMillis();
// do something
long time = System.currentTimeMillis() - start;

筆記:

  • 對象創建很快,即使它是多余的,Date對象也很小而且很便宜。 但是它會導致a)系統中的對象數量和b)測試中的一般噪聲(如果您嘗試對其進行內存分析)。 要減少變化(並加快代碼速度),您需要減少內存分配,尤其是冗余分配。
  • 這只能精確到1毫秒,如果你的系統在運行時糾正時間,它可能是不正確的(甚至是負數)但是,它很少以戲劇性的方式做到這一點,而是逐漸糾正時鍾意味着時間可能會出來一小部分。 鑒於由於系統上發生的其他事情導致的時間變化,如果這是您最大的問題,那么您將非常幸運。
  • 可以使用System.nanoTime()代替,但這可能會有它自己的漂移。 在較長的時間段內,例如小時,System.currentTimeMillis()可以更准確。
  • 如果您正在嘗試編寫微基准測試,我會確保代碼預熱。 即忽略前2-10秒,因為在這個階段代碼很可能不溫暖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM