今天玩topcoder, 发现“两次减法操作”竟然比“一次2倍乘法和一次加法”要慢一秒。下面是例程。
package practice;
import java.util.Calendar;
public class GuessinNextElement {
public int guessSlow(int[] A)
{
boolean flag=true;
if ((A[1]-A[0])==(A[2]-A[1]))
flag=false;
if (flag)
return A[A.length-1]*(A[2]/A[1]);
else
return A[A.length-1]+(A[2]-A[1]);
}
public int guessFast(int[] A)
{
boolean flag=true;
if ((A[1]*2)==(A[2]-A[0]))
flag=false;
if (flag)
return A[A.length-1]*(A[2]/A[1]);
else
return A[A.length-1]+(A[2]-A[1]);
}
public static void main(String[] args) {
int[] A={13,117,1053,9477,85293};
GuessinNextElement gne=new GuessinNextElement();
long total = System.currentTimeMillis();
for (long l=0;l<1000000000;l++)
gne.guessSlow(A);
total = System.currentTimeMillis()-total;
System.out.println("guessSlow: "+total);
total = System.currentTimeMillis();
for (long l=0;l<1000000000;l++)
gne.guessFast(A);
total = System.currentTimeMillis()-total;
System.out.println("guessFast: "+total);
}
}
结果:
guessSlow: 17594
guessFast: 16422