每百万次迭代打印一次消息

时间:2013-04-23 10:55:18

标签: java loops for-loop while-loop iteration

我需要编写一个循环,每百万次迭代打印一次消息。我想让它运行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
  }
}

3 个答案:

答案 0 :(得分: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,所以我摆脱了它。

答案 1 :(得分: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
  }
}

答案 2 :(得分:-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
  }
}