halny
halny

Reputation: 63

Python return time performance time.clock()

I have the following code where I want to measure time performance.

import time

def fibonacci(n):
    t0 = time.clock()
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        a = fibonacci(n-1)
        b = fibonacci(n-2)
    return a + b, time.clock()  

When I run it returns Type error: can only concatenate tuple (not "int") to tuple
How can I return result of the function together with time performance please? What am I missing here?

Upvotes: 0

Views: 123

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140305

a and b are results of your function, you're returning a tuple... Just time the main fibonacci call from outside the function, in a function wrapper for instance:

def time_fibonacci(n):
    start = time.clock()
    result = fibonacci(n)
    # return a tuple: result + cpu time
    return result, time.clock() - start  

and fixed fibonacci itself (without the clocking):

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        a = fibonacci(n-1)
        b = fibonacci(n-2)
    return a + b

Upvotes: 2

nosklo
nosklo

Reputation: 223152

if you want the function itself to return the time, you have to remember that this is a recursive function that calls itself, so you have to account for (and probably discard) the inner calls timing results. Also you have to edit all return statements:

def fibonacci(n):
    t0 = time.clock()
    if n == 0:
        return 0, time.clock() - t0
    elif n == 1:
        return 1, time.clock() - t0
    else:
        a, _ign = fibonacci(n-1)
        b, _ign = fibonacci(n-2)
    return a + b, time.clock() - t0 

Another approach would be to measure the time outside the function, that way you don't have to modify the function at all:

 t0 = time.clock()
 fibonacci(some_number) # call the original function without timing
 time_taken = time.clock() - t0

Upvotes: 1

Related Questions