【发布时间】: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