简体   繁体   English

Java Fib迭代和Fib递归时间比较

[英]Java Fib iterative and Fib recursive time comparison

Please if you could just check my work and help guide me through the System.currentTimeMillis() function. 请您检查一下我的工作并通过System.currentTimeMillis()函数帮助我。 I understand that it takes a snapshot of my computer time and then when I end it it takes another snap shot and I use the difference of those times to get my run time. 我知道这需要对计算机时间进行快照,然后在结束时进行快照,然后利用这些时间的差来获取运行时间。 Just not sure I'm implementing it properly as my times for my iterative function and my recursive are almost always identical or at most 1 off. 只是不确定我是否正确实现了它,因为我的迭代函数和递归时间几乎总是相同的,或者最多为1。 I'm confused a little as to if my start time is called again before my iterative starts or if really my time check for iterative time is iterative plus my recursive function. 我对于在迭代开始之前是否再次调用我的开始时间还是是否真的对迭代时间进行时间检查是迭代加上递归函数感到困惑。 Should I have my total iterative time be endTimeIter - endTimeRecur? 我应该让我的总迭代时间为endTimeIter-endTimeRecur吗? Any help is appreciated. 任何帮助表示赞赏。

public class FibTest{
    public static void main (String[] args){
        long startTime = System.currentTimeMillis();
        int n = 40;
        System.out.println("The 40th Fibonacci number per my recursive function is: " +    fibRecur(n));
           long endTimeRecur = System.currentTimeMillis();
           long totalTimeRecur = endTimeRecur - startTime;
        System.out.println("The 40th Fibonacci number per my recursive function is: " + fibIter(n));
           long endTimeIter = System.currentTimeMillis();
           long totalTimeIter = endTimeIter - startTime;
        System.out.println("The time it took to find Fib(40) with my recursive method was: " + totalTimeRecur);
        System.out.println("The time it took to find Fib(40) with my iterative method was: " + totalTimeIter);
    }
    public static int fibRecur(int n){
        if (n < 3) return 1;
        return fibRecur(n-2) + fibRecur(n-1);
    }
    public static int fibIter(int n){
        int fib1 = 1;
        int fib2 = 1;
        int i, result = 0;
        for (i = 2; i < n; i++ ){
            result = fib1 + fib2;
            fib1 = fib2;
            fib2 = result;
        }
        return result;
    }  
 }

That's one way of how the time difference must be done 这是必须完成时差的一种方式

long time = System.currentTimeMillis();
methodA();
System.out.println(System.currentTimeMillis() - time);

time = System.currentTimeMillis();
methodB();
System.out.println(System.currentTimeMillis() - time);

In addition to Amir's answer: 除了Amir的答案:

One bug in your program is that you print 程序中的一个错误是您打印

System.out.println("The 40th Fibonacci number per my recursive function is: " + fibIter(n));

I think what you want to say is: 我想你想说的是:

System.out.println("The 40th Fibonacci number per my iterative function is: " + fibIter(n));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM