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

前端 未结 12 1803
礼貌的吻别
礼貌的吻别 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条回答
  •  萌比男神i
    2020-12-02 11:04

    I was playing around with timing in Python 3.7 today and trying to pass functions and variables into the timer. This is what I came up with.

    import re
    
    text = "This         is      a  test of the      emergency broadcast       system"
    
    def regex(text):
        return re.sub(r"(\s)\1{1,}", r"\1", text)
    
    def loop_while(text):
        if "  " in text:
            while "  " in text:
                text = text.replace("  ", " ")
    
        return text
    
    if __name__ == "__main__":
        import timeit
    
        callable_functions = [item for item in locals().items() if callable(item[1])]
    
        for func_name, func in callable_functions:
            elapsed_time = timeit.timeit(f"{func_name}(text)", globals=globals(), number=100000)
            print(f"{func_name}: {elapsed_time} \n{func(text)}\n")
    

    This outputs:

    regex: 1.378352418
    This is a test of the emergency broadcast system

    loop_while: 0.15858950299999997
    This is a test of the emergency broadcast system

    Then all it takes to test a new version is adding in a new function. Something like:

    def split_join(text):
        return " ".join(text.split())
    

    Now it outputs:

    regex: 1.378352418
    This is a test of the emergency broadcast system

    loop_while: 0.15858950299999997
    This is a test of the emergency broadcast system

    split_join: 0.05700970800000005
    This is a test of the emergency broadcast system

提交回复
热议问题