张芷铭的个人博客

tqdm(阿拉伯语"进步")是 Python 进度条库,为循环提供实时反馈,性能开销接近 O(1)。

核心原理

基于迭代器装饰模式,通过 __iter____next__ 跟踪进度,使用指数平滑算法估算剩余时间。

性能开销公式:

$$\text{overhead} = O(1) + \frac{C}{n}$$

适用场景

适用不适用
大数据处理极短循环(<0.1秒)
文件批量下载无法预测总数的流式处理
模型训练非迭代型任务
网络爬虫

基础用法

1
2
3
4
5
from tqdm import tqdm
import time

for i in tqdm(range(100), desc="处理中"):
    time.sleep(0.1)

高级功能

嵌套进度条

1
2
3
for i in tqdm(range(3), desc='外层'):
    for j in tqdm(range(5), desc='内层', leave=False):
        time.sleep(0.1)

Pandas 集成

1
2
tqdm.pandas()
df['new_col'] = df['col'].progress_apply(lambda x: x**2)

并行处理

1
2
3
4
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor() as executor:
    results = list(tqdm(executor.map(process, items), total=len(items)))

性能优化

1
2
3
4
5
6
7
8
9
# 减少更新频率
tqdm(..., mininterval=0.5)

# 禁用无终端环境
tqdm(..., disable=not sys.stdout.isatty())

# asyncio 支持
async for i in tqdm.async_(async_iter, total=100):
    await process(i)

实用示例

下载文件带进度

1
2
3
4
5
6
7
8
import requests

response = requests.get(url, stream=True)
total = int(response.headers.get('content-length', 0))

with open("file.zip", "wb") as f:
    for data in tqdm(response.iter_content(1024), total=total//1024, unit='KB'):
        f.write(data)

自定义格式

1
2
bar_format = '{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]'
tqdm(..., bar_format=bar_format)

替代方案对比

特性tqdmalive-progressprogressbar2
Jupyter 支持
并行处理
自定义样式

参考资源

Comments