简体   繁体   English

使用 timeit.timeit 测量 function 和 arguments 的运行时间

[英]Measure runtime of function with arguments using timeit.timeit

I would like to create a function. The code doesn't work, but you can get the idea what I want to get:我想创建一个 function。代码不起作用,但您可以理解我想要得到的内容:

def time_test(func, test_data: int) -> float:
    # should return a runtime of given function
    return timeit(stmt=func(test_data), number=10000)

Obviously, I do have to pass as stmt something callable or a string with executable code.显然,我必须将可调用的东西或带有可执行代码的字符串作为stmt传递。 That's why it doesn't work, but I don't know how to do this in a correct way.这就是为什么它不起作用,但我不知道如何以正确的方式做到这一点。

Example how I want to use time_test() function:例如我想如何使用time_test() function:

from timeit import timeit
# To be tested
def f1(argument_ops):
    result = 0
    for i in range(argument_ops):
        result += 4
    return result

def f2(argument_ops):
    result = 0
    for i in range(argument_ops):
        for j in range(argument_ops):
            result += 4
    return result

# test function to be implemented
def time_test(func, test_data: int) -> float:
    runtime = 0
    # implement this, it should return a runtime of a given function. Function needs
    # argument test_data.
    return runtime

# example of usage
print(time_test(f1, 96))
print(time_test(f2, 24))

Actually, I think you can use the globals argument, which takes a namespace in which to execute the statement, to do this relatively easily.实际上,我认为您可以使用globals参数来相对轻松地完成此操作,该参数采用在其中执行语句的名称空间。 Something to the effect of:有以下效果:

def time_test(func, test_data: int) -> float:
    gs = dict(func=func, test_data=test_data)
    runtime = timeit("func(test_data)", globals=gs)
    # implement this, it should return a runtime of a given function. Function needs argument test_data.
    return runtime

Note, by default this times how long it takes to the statement 1000000 times.注意,默认情况下this times语句1000000次需要多长时间。

I would suggest doing it this way which involves passing the function definition to the time_test() function as well as the function name and arguments:我建议这样做涉及将 function 定义传递给time_test() function 以及 function 名称和 arguments:

from timeit import timeit

# To be tested
f1_def = """
def f1(argument_ops):
    result = 0
    for i in range(argument_ops):
        result += 4
    return result
"""

f2_def = """
def f2(argument_ops):
    result = 0
    for i in range(argument_ops):
        for j in range(argument_ops):
            result += 4
    return result
"""

# test function
def time_test(func, test_data: int, setup: str) -> float:
    stmt = f'{func}({test_data!r})'
    runtime = timeit(stmt, setup)
    return runtime

# example of usage
print(time_test('f1', 96, setup=f1_def))  # -> 4.069019813000001
print(time_test('f2', 24, setup=f2_def))  # -> 34.072881441999996

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM