python 3.x 时间问题 '<timeit-src>'

python 3.x problem with timeit '<timeit-src>'

timeit 不工作。 我想计算并打印一个函数需要 运行 的时间。 该功能运行良好,但时间不... 请好心人帮帮我

'''python code''' 导入时间

def add_numbers(x,y):
    '''function to add together'''
    sum = x + y
    return sum

x = 5
y = 4

print("The sum is", add_numbers(x, y))

print(timeit.timeit(add_numbers))

谢谢!

您需要将函数名称作为字符串传递并传递设置:

import timeit

def add_numbers(x, y):
    sum = x + y
    return sum

x = 5
y = 4

print("The sum is", add_numbers(x, y))

print(timeit.timeit(stmt="add_numbers", setup="from __main__ import add_numbers"))

您可以将 __main__ 更改为您的函数所在的任何模块。