ZetCode

Python timeit

最后修改于 2025 年 2 月 16 日

在本文中,我们将展示如何使用 Python 的 timeit 模块来测量小代码片段的执行时间。timeit 模块对于性能测试和优化特别有用,因为它通过多次运行代码来提供准确的计时结果。

timeit 模块是 Python 标准库的一部分,因此无需额外安装。

timeit 的基本用法

timeit 模块提供了 timeit 函数,可用于测量语句的执行时间。该函数具有以下参数:

示例:计时简单语句

以下示例演示了如何对简单的算术运算进行计时。

main.py
import timeit

# Time the execution of the statement "5 + 5"
stm = "5 + 5"
print(timeit.timeit(stmt=stm, number=50_000_000))

在此程序中,timeit.timeit 函数用于在 5000 万次迭代中测量语句 5 + 5 的执行时间。

$ python main.py
0.7231783000170253

示例:计时指数运算

以下示例比较了计算指数的两种方法的执行时间:使用 ** 运算符和 pow 函数。

main.py
import timeit

# Time the execution of the statement "3 ** 3"
stm = "3 ** 3"
print(timeit.timeit(stmt=stm, number=50_000_000))

# Time the execution of the statement "pow(3, 3)"
stm = "pow(3, 3)"
print(timeit.timeit(stmt=stm, number=50_000_000))

在此程序中,timeit.timeit 函数用于在 5000 万次迭代中测量语句 3 ** 3pow(3, 3) 的执行时间。

$ python main.py
0.6393674000282772
3.6729515999904834

比较循环:for vs while

以下示例比较了 for 循环和 while 循环的执行时间。

main.py
import timeit

# Define a function with a for loop
mycode = ''' 
def fn(): 
    for e in range(10000): 
        print(e)
'''

# Define a function with a while loop
mycode2 = ''' 
def fn():
    i = 0
    while i < 10000:
        print(i)
        i += 1
'''

# Time the execution of the for loop
print(timeit.timeit(stmt=mycode, number=5_000_000))

# Time the execution of the while loop
print(timeit.timeit(stmt=mycode2, number=5_000_000))

在此程序中,timeit.timeit 函数用于在 500 万次迭代中测量 for 循环和 while 循环的执行时间。

$ python main.py
0.44675440003629774
0.4859266999992542

使用装饰器进行计时

以下示例演示了如何使用 timeit 模块创建装饰器来测量函数的执行时间。

main.py
import timeit

# Define a decorator for timing functions
def time_it(fn):
    def wrapper(*args, **kwargs):
        t0 = timeit.default_timer()
        fn(*args, **kwargs)
        t1 = timeit.default_timer()
        print("{0:.10f} seconds".format(t1 - t0))
    return wrapper

# Apply the decorator to functions
@time_it
def fstring_fn(vals):
    print("fstring_fn:", f"{vals[0]} {vals[1]} {vals[2]} {vals[3]} {vals[4]}")

@time_it
def format_fn(vals):
    print("format_fn:", "{0} {1} {2} {3} {4}".format(*vals))

@time_it
def oldschool_fn(vals):
    print("oldschool_fn:", "%s %s %s %s %s" % vals)

# Test data
data = ('sky', 'pen', 23.0, -11, True)

# Call the decorated functions
fstring_fn(data)
print('---------------')
format_fn(data)
print('---------------')
oldschool_fn(data)

在此程序中,time_it 装饰器用于测量三个函数 fstring_fnformat_fnoldschool_fn 的执行时间。

$ python main.py
fstring_fn: sky pen 23.0 -11 True
0.0002156000 seconds
---------------
format_fn: sky pen 23.0 -11 True
0.0002937000 seconds
---------------
oldschool_fn: sky pen 23.0 -11 True
0.0003093000 seconds

来源

Python timeit - 文档

在本文中,我们展示了如何使用 Python 的 timeit 模块来测量小代码片段的执行时间。timeit 模块是性能测试和优化的强大工具。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Python 教程