需要至少缓慢执行至少5秒

-5 java arrays performance execution

我编写了一个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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Aks*_*hay 7

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

Thread.sleep(5000);
Run Code Online (Sandbox Code Playgroud)

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

另请注意,参数是毫秒,而不是秒.

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

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