1
votes

Here is the code as I currently have it:

def F(n):
    t=time.time()
    if n==0:
        return (0)
    elif n==1:
        return (1)
    else:
        return (F(n-1)+F(n-2))
    t1==time.time()
    return t
    F_time==t1-t
    print ('It took',F_time,'seconds to sort',n,'values using recursion')

I'm trying to print n numbers of the Fibonacci sequence and take the time before and after, but because of the return statements, it won't accept the variable after the return, nor the following print statement.

2

2 Answers

1
votes

Anything after a return statement will never be executed. A return statement instantly terminates the function and "returns" to the caller. So it's really not possible.

There are two ways to get (nearly) the same result though.

Method #1:

The time it takes to execute a return statement is almost negligable. Therefore you can move the necessary benchmark code above the return and get an almost identical result as if it actually executed after a 'return' statement.

def F(n):
    t=time.time()
    if n==0:
        return (0)
    elif n==1:
        return (1)
    else:
        return (F(n-1)+F(n-2))
    t1==time.time()
    F_time==t1-t
    print ('It took',F_time,'seconds to sort',n,'values using recursion')
    return t

Method #2:

Put your timing code outside the function, this is the preferred method.

def F(n):

    if n==0:
        return (0)
    elif n==1:
        return (1)
    else:
        return (F(n-1)+F(n-2))
    return t

t=time.time()
F(5)
t1==time.time()
F_time==t1-t
print ('It took',F_time,'seconds to sort',5,'values using recursion')

Hope this helped, good luck!

1
votes

In order to really execute things after the return statement(s) inside a function use try-finally like this:

# platform independent high-resolution clock
from timeit import default_timer as timer  

def F(n):
    t = timer()
    try:
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return (F(n - 1) + F(n - 2))
    finally:
        t1 = timer()
        F_time = t1 - t
        print(u"F(%s) took %.2fµs seconds" % (n, F_time * 1e6))

if __name__ == '__main__':
    print("RESULT:", F(4))

Output:

F(1) took 0.92µs seconds
F(0) took 0.84µs seconds
F(2) took 429.78µs seconds
F(1) took 0.84µs seconds
F(3) took 520.12µs seconds
F(1) took 0.67µs seconds
F(0) took 0.75µs seconds
F(2) took 90.85µs seconds
F(4) took 700.82µs seconds
RESULT: 3

Note: in that example here the timings for n > 1 of course include time for printing to stdout in nested recursive calls, which then dominate timing in that trivial example.