【问题标题】:Need to SLOW DOWN EXECUTION BY atleast 5 SECONDS需要将执行速度减慢至少 5 秒
【发布时间】:2014-07-16 19:06:40
【问题描述】:

我写了一个Java程序,用来计算整数不同循环中的最大循环。我的代码非常快,在我的四核 A8 AMD 处理器上只需几毫秒即可获得结果。

我想将执行速度减慢至少 5 秒。有什么我可以添加到代码中来减慢它的速度吗?

import java.util.Scanner;

class SNASA {
    public static void main(String args[]) {
        long i,j,n,max=0, pos=0, x, y;
        long count=0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the positive integer :");
        while(sc.hasNextLong()) {
            x=System.currentTimeMillis();
            i = sc.nextLong();
            long arr[] = new long [60000000];
            for(long p=i/2;p<i;p++) {
                arr[(int)p]=0;
            }
            for(j=1;j<=i;j++) {
                n=j;
                count=0;
                tag:while(n!=1) {
                    if(n<60000000) {
                        if(arr[(int)(n-1)]!=0) {
                            count = count + arr[(int)(n-1)];
                            break tag;
                        }
                    }
                    if(n%2==0) {
                        n = n/2;
                        count++;
                    } else {
                        n = (2*n)+n+1;
                        count++;
                    }
                }
                if(j<60000000)
                    arr[(int)(j-1)]=count;
                if(count>max) { 
                    max=count; pos=j; 
                }
                count=0;
            }
            y=System.currentTimeMillis();
            System.out.println("Maximum Cycle length occurs at "+pos+" and the number of steps in cycle "+max+"\n Total time taken is "+(y-x)+"ms");
        }
    }
}

【问题讨论】:

  • 答案显然涉及降低 CPU 的时钟速度。
  • 感谢您的回答。 :)
  • @admdrew 我可能会因为这样说而被激怒,但我不认为时钟速度足够低的 CPU 能够在合理的时间内启动 JVM。 :)
  • 您希望 Thread.sleep() 不提供哪些特定功能?
  • 解释为什么你需要放慢你的进程。我们没有神奇的水晶球来解释您对工作的具体要求以完全理解问题。

标签: java arrays performance execution


【解决方案1】:

您可以按如下方式暂停执行 5 秒:

Thread.sleep(5000);

这将在该行完全停止程序,等待指定的持续时间,然后继续。

还要注意parameter is milliseconds, not seconds

由于程序将在此行放置的任何位置暂停,如果您希望总延迟量取决于您运行的迭代次数,您可以将其保留在循环内,每次循环运行时都会有延迟.

for (int i = 0; i < 10; i++)
{
    Thread.sleep(1000); //Delays 1s 10 times; 10s overall delay
}

【讨论】:

    【解决方案2】:

    使用Thread.sleep(5000) 添加延迟 5 秒。

    使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,取决于系统计时器和调度程序的精度和准确性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多