how to pass parameters of a function when using timeit.Timer()

前端 未结 12 1731
礼貌的吻别
礼貌的吻别 2020-12-02 10:19

This is the outline of a simple program

# some pre-defined constants
A = 1
B = 2

# function that does something critical
def foo(num1, num2):
    # do somet         


        
相关标签:
12条回答
  • 2020-12-02 10:51

    I prefer creating a static class with all the Data ready to be picked up prior of running the timer.

    Another note, it is better to do test runs in function rather then in the global space, as the global space isn't taking advantage of FAST_LOAD Why does Python code run faster in a function?

    class Data(object):
        """Data Creation"""
        x = [i for i in range(0, 10000)]
        y = tuple([i for i in range(0, 10000)])
        def __init__(self):
            pass
    
    import timeit
    
    def testIterator(x):
        for i in range(10000):
            z = i
    
    
    print timeit.timeit("testIterator(Data.x)", setup="from __main__ import testIterator, Data", number=50)
    print timeit.timeit("testIterator(Data.y)", setup="from __main__ import testIterator, Data", number=50)
    
    0 讨论(0)
  • 2020-12-02 10:53

    I usually create an extra function:

    def f(x,y):
        return x*y
    
    v1 = 10
    v2 = 20
    
    def f_test():
        f(v1,v2)
    
    print(timeit.timeit("f_test()", setup="from __main__ import f_test"))
    
    0 讨论(0)
  • 2020-12-02 10:53

    Here is an example of how to compartmentalize the timing routine, without calling globals

    def foo(a, b):
        '''Do something to `a` and `b`'''
        return a + b
    
    def time_foo():
        '''Create timer object simply without using global variables'''
        import timeit
    
        _foo = foo
        a = 1
        b = 2
    
        # Get `Timer` oject, alternatively just get time with `timeit.timeit()`
        t = timeit.Timer('_foo(a, b)', globals=locals())
    
        return t
    

    You could even generalize this if you wanted to use the same timeit function to time other functions. Here is an example with your example main() routine:

    def foo1(a, b):
        '''Add `a` and `b`'''
        return a + b
    
    def foo2(a, b):
        '''More math on `a` and `b`'''
        return (a**2 * b)**2
    
    def time_foo(func, **kwargs):
        '''Create timer object simply without using global variables'''
        import timeit
        return timeit.timeit('func(**kwargs)', globals=locals())
    
    def run():
        '''Modify inputs to foo and see affect on execution time'''
    
        a = 1
        b = 2
        for i in range(10):
            # Update `a` and `b`
            a += 1
            b += 2
            # Pass args to foo as **kwargs dict
            print('foo1 time: ', time_foo(foo1, **{'a':a, 'b':b}))
            print('foo2 time: ', time_foo(foo2, **{'a':a, 'b':b}))
    
        return None
    
    0 讨论(0)
  • 2020-12-02 10:57

    Supposing that your module filename is test.py

    # some pre-defined constants
    A = 1
    B = 2
    
    # function that does something critical
    def foo(n, m):
        pass
    
    # main program.... do something to A and B
    for i in range(20):
        pass
    
    import timeit
    t = timeit.Timer(stmt="test.foo(test.A, test.B)", setup="import test")  
    print t.timeit(5)
    
    0 讨论(0)
  • 2020-12-02 10:59

    The code snippets must be self-contained - they cannot make external references. You must define your values in the statement-string or setup-string:

    import timeit
    
    setup = """
    A = 1
    B = 2
    
    def foo(num1, num2):
        pass
    
    def mainprog():
        global A,B
        for i in range(20):
            # do something to A and B
            foo(A, B)
    """
    
    t = timeit.Timer(stmt="mainprog()" setup=setup)
    print(t.timeit(5))
    

    Better yet, rewrite your code to not use global values.

    0 讨论(0)
  • 2020-12-02 11:01

    There is a much simpler solution (at least for Python 3), you can cause the code to be executed within your current global namespace:

    t = timeit.Timer(stmt="foo(num1,num2)", globals=globals())

    https://docs.python.org/3/library/timeit.html#examples I know globals are not preferred, but if you are just making a quick script to check something I think this is the easiest implementation.

    0 讨论(0)
提交回复
热议问题