我試圖使用以下代碼與System.nanoTime()
來測量代碼已用時間。爲什麼我使用System.nanoTime()獲得負時間?
public static void main(String[] args) throws Exception {
while (true) {
long start = System.nanoTime();
for (int i = 0; i < 10000; i++)
;
long end = System.nanoTime();
long cost = end - start;
if (cost < 0) {
System.out.println("start: " + start + ", end: " + end + ", cost: " + cost);
}
}
}
我也得到這樣的結果:
start: 34571588742886, end: 34571585695366, cost: -3047520
start: 34571590239323, end: 34571586847711, cost: -3391612
start: 34571651240343, end: 34571648928369, cost: -2311974
start: 34571684937094, end: 34571681543134, cost: -3393960
start: 34571791867954, end: 34571788878081, cost: -2989873
start: 34571838733068, end: 34571835464021, cost: -3269047
start: 34571869993665, end: 34571866950949, cost: -3042716
start: 34571963747021, end: 34571960656216, cost: -3090805
start: 34571965020545, end: 34571961637608, cost: -3382937
start: 34572010616580, end: 34572007613257, cost: -3003323
爲什麼我得到負值?
(OS:視窗XP SP3,JAVA:jdk1.6u27)
無法在具有Java™SE運行時環境(版本1.6.0_26-b03)的Linux上重現。無論如何,你爲什麼抱怨?當Java在九十年代人們抱怨緩慢時,現在它*速度太快了,而且人們仍然抱怨:-) – stivlo
抱怨?我只是找不到測量代碼執行時間的正確方法。與快或慢無關。 – Freewind
相關:http://stackoverflow.com/questions/3274892/why-is-my-system-nanotime-broken – stivlo