2

I know the title is a little bit confusing.

So let me take this code as example:

import timeit

def test1(x,y):
    return x*y

def time_cost(func):
    start = timeit.default_timer()
    func()
    stop = timeit.default_timer()

    print(stop - start)

time_cost(test1)

I want to give test1's two parameter, x and y, to time_cost function.

But I don't know how to do so.

I have tried this before:

import timeit

def test1(x,y):
    return x*y

def time_cost(func):
    start = timeit.default_timer()
    func
    stop = timeit.default_timer()

    print(stop - start)

time_cost(test1(1,2))  

It can run but the result is so weird that I believe this is wrong.

So how to do this? Thank you all.

2
  • You can't give x and y as arguments to time_cost if it only accepts one agrument (func). If you want time_cost to accept other arguments, then you need to rewrite it so it accepts those other arguments. Commented Apr 27, 2016 at 3:50
  • You'll want to read up on the terms: closures, decorators, wrappers. The basic idea is that you replace ("wrap ") your function with a new function that does what you want and handles the arguments the way you want. Commented Apr 27, 2016 at 3:51

2 Answers 2

4

Return a function that does what you want.

def time_cost(func):
    def run(*args, **kwargs):
        start = timeit.default_timer()
        func(*args, **kwargs)
        stop = timeit.default_timer()

        print(stop - start)
    return run

Then call it.

time_cost(test1)(1, 2)
Sign up to request clarification or add additional context in comments.

Comments

2

Give this a try.

from functools import wraps
import timeit

def time_cost(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = timeit.default_timer()
        result = func(*args, **kwargs)
        stop = timeit.default_timer()
        print(stop - start)
        return result
    return wrapper

test1 = time_cost(test1)
test1(1,2)

This kind of function is called a decorator. Also called a wrapper, or a closure.

You can also use this with the decorator syntax:

@time_cost
def test1(x,y):
    return x*y

test1(1,2)

This does the same as the code above.

2 Comments

Your method seems a little bit arcane. Whatever, I am really appreciate for your help!
@MarsLee This is actually probably the preferred method for doing this kind of thing in Python. And it is identical to the first answer by IVA, I'm just using it slightly differently. See: python.org/dev/peps/pep-0318/#abstract

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.