Search code examples
pythontimedecoratorpow

Python - measure function execution time with decorator


I have the next problem: For example, I have a function (this is just an example to make things simple) called my_pow, that takes two arguments and return a^b, and it looks like this:

def my_pow(a, b):
    res = a ** b
    return res
    # or just return a ** b, it doesn't really matter

And I have a decorator that should measure for how long did the decorated function ran.

def decorator_timer(some_function):
    from time import time

    def wrapper(*args, **kwargs):
        t1 = time()
        result = some_function(*args, **kwargs)
        return result, time()-t1
    return wrapper

And the problem is, I can't really measure the time for how long did it took a function to calculate for example 99999 ** 99999. I can either calculate it and print res, this way I'll get a correct execution time but None will be returned from a my_pow() function, or I can return res, but the time it took to run will be something 0.0001, though obviously decorated function is running for much longer, actually around 3 seconds. Is there a way to measure how long did it take to run that function, and at the same time return a res value from a function?


Solution

  • Your function is running in 0.0001 something seconds. But since the number is so large, it takes almost 3 seconds to print it. So your code is working, I/O(print) is just slow. You can see it yourself if you only print the time it took.

    To further demonstrate this and also add emil's comment

    def decorator_timer(some_function):
        from time import time
    
        def wrapper(*args, **kwargs):
            t1 = time()
            result = some_function(*args, **kwargs)
            end = time()-t1
            return result, end
        return wrapper
    
    
    @decorator_timer
    def my_pow(a, b):
        res = a ** b
        return res
        # or just return a ** b, it doesn't really matter
    
    result, exec_time = my_pow(99999 , 99999)
    print(exec_time) # prints after 0.07347989082336426 seconds
    print(result) # takes ~3 seconds