【发布时间】:2015-06-21 16:23:12
【问题描述】:
以下 Java 方法旨在以 nLoopsPerSecond 次在 seconds 秒内每秒打印数字 i:
public void test(int nLoopsPerSecond, int seconds) {
double secondsPerLoop = 1.0/(double)nLoopsPerSecond;
long startTime = System.currentTimeMillis();
long currentTime;
int i = 0;
while ((currentTime = System.currentTimeMillis()) < startTime + seconds*1000) {
System.out.println(i++);
while (System.currentTimeMillis() < currentTime + secondsPerLoop*1000);
}
}
通过以下调用:
test(1000,1);
我希望这种方法可以执行System.out.println(i++); 1,000 次,但我只得到了 63 次。
当我尝试使用此代码查看每个循环实际使用多少秒时
public void test(int nLoopsPerSecond, int seconds) {
double secondsPerLoop = 1.0/(double)nLoopsPerSecond;
long startTime = System.currentTimeMillis();
long currentTime;
int i = 0;
while ((currentTime = System.currentTimeMillis()) < startTime + seconds*1000) {
while (System.currentTimeMillis() < currentTime + secondsPerLoop*1000);
System.out.println(System.currentTimeMillis() - currentTime);
}
}
我希望它在每个循环中打印1 毫秒,但它会打印15 或16 毫秒。
请提出我的代码有什么问题。
【问题讨论】:
-
我建议您输入您尝试执行的确切代码。这不会编译。例如 -
seccond是什么?另外-为什么在while循环中有while循环? -
System.out.println可能无法每秒向控制台输出 1000 次。少得多。 -
作为在循环中使用
printlln()的替代方法,您可以使用您希望打印的值填充数据结构,然后在循环后立即显示它们。尝试一个ArrayList构造为已经大小为 1000 或尝试一个旧学校 int 数组大小为 1000。 -
@jite 我不这么认为,因为当我删除内部
while时,它最多打印 90,000++ -
出于您的目的,看起来
System.nanoTime()会更有用,因为您没有从纪元开始测量时间。 stackoverflow.com/a/351571/1493294
标签: java loops time while-loop