Stopwatch

語言: CN / TW / HK
/**
* An object that accurately measures <i>elapsed time</i>: the measured duration between two
* successive readings of "now" in the same process.
*一個精確計算消耗時間的對象:計算在同一進程中兩次連續讀取當前時間之間持續的時間
* <p>In contrast, <i>wall time</i> is a reading of "now" as given by a method like
* { @link System#currentTimeMillis()}, best represented as an { @link Instant}. Such values
* <i>can</i> be subtracted to obtain a { @code Duration} (such as by { @code Duration.between}), but
* doing so does <i>not</i> give a reliable measurement of elapsed time, because wall time readings
* are inherently approximate, routinely affected by periodic clock corrections. Because this class
* (by default) uses { @link System#nanoTime}, it is unaffected by these changes.
*作為對照,實際時間是讀取當前時間,就像System.currentTimeMillis()方法,一瞬間的最好代表。這種值相減可以得到一段時間,但是這樣得不到準確的消耗的時間,因為實際時間讀取是本質上近似的, 經常受到週期性時鐘校正的影響。因為這個類使用System.nanoTime方法,它不受這些變化的影響
* <p>Use this class instead of direct calls to {@link System#nanoTime} for two reasons:
*用這個類代替直接調用System.nanoTime有兩個原因
* <ul>
* <li>The raw {@code long} values returned by {@code nanoTime} are meaningless and unsafe to use
* in any other way than how {@code Stopwatch} uses them.
任何地方使用nanoTime返回的這個原生的long類型的值相對於Stopwatch使用它相比,毫無意義而且不安全
* <li>An alternative source of nanosecond ticks can be substituted, for example for testing or
* performance reasons, without affecting most of your code.
一個可供選擇的資源是時間片段可以被替換,例如為了測試或性能原因,不影響你的大部分代碼
* </ul>
*
* <p>Basic usage:
*
* <pre>{@code
* Stopwatch stopwatch = Stopwatch.createStarted();
* doSomething();
* stopwatch.stop(); // optional
*
* Duration duration = stopwatch.elapsed();
*
* log.info("time: " + stopwatch); // formatted string like "12.3 ms"
* }</pre>
*
* <p>The state-changing methods are not idempotent; it is an error to start or stop a stopwatch
* that is already in the desired state.
*這個狀態更改的方法不是冪等的,開始或停止一個已經處於期望狀態的stopwatch對象是一個錯誤。
* <p>When testing code that uses this class, use {@link #createUnstarted(Ticker)} or {@link
* #createStarted(Ticker)} to supply a fake or mock ticker. This allows you to simulate any valid
* behavior of the stopwatch.
*當測試代碼使用這個類,使用createUnstarted(Ticker)或createStarted(Ticker)提供一個假的或模擬的ticker,這裏允許你模擬任何stopwatch有效的行為
* <p><b>Note:</b> This class is not thread-safe.
*這個類是非線程安全的。
* <p><b>Warning for Android users:</b> a stopwatch with default behavior may not continue to keep
* time while the device is asleep. Instead, create one like this:
*安卓用户的警告:設備休眠的時候stopwatch默認可能不會繼續計算。代替的創建一個類似這種的代碼:
* <pre>{@code
* Stopwatch.createStarted(
* new Ticker() {
* public long read() {
* return android.os.SystemClock.elapsedRealtimeNanos();
* }
* });
* }</pre>
*
* @author Kevin Bourrillion
* @since 10.0
*/
 
總結:stopwatch主要功能就是兩次star和stop調用之間的時間,還可以多次累加、可以重置。非線程安全的。
增加ticker的作用是可以自己替換和實現時間的讀取。