0

我需要编写一个循环,每百万次迭代打印一次消息。我想让它运行 10 秒(时钟时间)以查看打印了多少条语句。

我想我现在只是把自己绑起来了……

public class OneInAMillion{
  public static void main(String []args){
    long startTime = System.currentTimeMillis();  //time at start of execution
    long endTime = startTime + 10000;  //time at end of execution (10000 = 10 seconds)
    int count = 1;

    while(System.currentTimeMillis() < endTime) { //run this before 10 seconds is up
      for (int i = 0; i < count; i++) {
        if(i % 1000000 == 0) {
            System.out.println("Iteration: " + count++);  //print every millionth iteration
        }
      }
    }

    System.out.println("Time up!"); //print once loop finishes
  }
}
4

3 回答 3

5

你在循环中有一个循环。想想每个循环的作用——第一个循环会一直持续到 10 秒。另一个将简单地从 0 开始变为 1,在 while 循环的下一次迭代中,它将从 0 变为 2,然后从 0 变为 3,依此类推。当它为 0(很多)时它也会打印,因为 0%1000000 是 0。

尝试将它们组合成一个循环。这可以通过摆脱 while 循环并仅使用带有 while 循环条件的 for 循环来完成,如下所示:

  public static void main(String[] args) {
     long endTime = System.currentTimeMillis() + 10000;  //time at end of execution (10000 = 10 seconds)
     for (int i = 1; System.currentTimeMillis() < endTime; i++) {
        if(i % 1000000 == 0) {
            System.out.println("Iteration: " + i/1000000);  //print every millionth iteration
        }
      }
      System.out.println("Time up!"); //print once loop finishes
  }

请注意,count它将始终是 i/1000000,所以我摆脱了它。

于 2013-04-23T11:04:19.407 回答
0

摆脱你的for循环,i++在你之前做if和打印i而不是计数,你应该被设置。

public class OneInAMillion{
  public static void main(String []args){
    long startTime = System.currentTimeMillis();  //time at start of execution
    long endTime = startTime + 10000;  //time at end of execution (10000 = 10 seconds)
    //int count = 1;
    int i = 0;
    while(System.currentTimeMillis() < endTime) { //run this before 10 seconds is up
        i++;
        if(i % 1000000 == 0) {
            System.out.println("Iteration: " + i);  //print every millionth iteration
        }
    }

    System.out.println("Time up!"); //print once loop finishes
  }
}
于 2013-04-23T11:03:27.873 回答
-1

您的 for 循环退出条件会干扰您的 while 循环退出条件,并阻止它在您期望的时候被评估。摆脱 while 循环:

public class OneInAMillion{
  public static void main(String []args){
    long startTime = System.currentTimeMillis();  //time at start of execution
    long endTime = startTime + 10000;  //time at end of execution (10000 = 10 seconds)
    int count = 1;

    for (int i = 0; i < count; i++) {
      if(System.currentTimeMillis() >= endTime) {
        break;
      }

      if(i % 1000000 == 0) {
        System.out.println("Iteration: " + count++);  //print every millionth iteration
      }
    }


    System.out.println("Time up!"); //print once loop finishes
  }
}
于 2013-04-23T11:05:38.467 回答