我试图计算单次迭代在for循环中所花费的时间量我写的是用Java将行写入文件。环顾四周之后,人们用来做这件事的方法似乎是在执行开始和结束时抓住系统时间并减去这些结果。这是我的代码中的内容:
String content;
for (int i = 0 ; i < 100; i += 1 ) {
long startTime = System.nanoTime();
content = "Currently writing line " + i " to the file.";
myBufferedWriter.write(content);
long endTime = System.nanoTime();
System.out.println("This iteration took: " + (endTime - startTime) " time.");
}
然而,看看我的结果我得到的大部分都是这样的:
This iteration took: 1000 time
This iteration took: 1000 time
This iteration took: 0 time
This iteration took: 1000 time
...
This iteration took: 24000 time
This iteration took: 1000 time
This iteration took: 0 time
This iteration took: 17000 time
等等。基本上大多数迭代看起来都像是以类似的速度执行,但为什么有时候两端的频率出现了疯狂的波动呢?有时它最终会很快进入(没有时间差异?),有时需要更长的时间。是什么给了什么?