我试图使用以下代码与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