Python运行进度条显示 代码及其应用示例 包含预估完成时间 与已执行时间

展示效果

在这里插入图片描述

上代码

import time
import sys


def display_progress(total_count, completed_count, start_time, bar_length=50):
    """
    显示进度信息的函数,具有固定长度的进度条。

    :param total_count: 总数量
    :param completed_count: 已完成数量
    :param start_time: 开始执行时间
    :param bar_length: 进度条的长度(默认为50)
    """
    # 计算已完成的百分比
    percent_complete = completed_count / total_count

    # 计算进度条上显示的#的数量
    hash_count = int(round(percent_complete * bar_length))

    # 计算已经过去的时间
    elapsed_time = time.time() - start_time

    # 如果已完成任务大于0,计算预计剩余时间
    if completed_count > 0:
        total_estimated_time = elapsed_time / percent_complete
        remaining_time = total_estimated_time - elapsed_time
    else:
        remaining_time = 0  # 如果没有完成任何任务,剩余时间未知

    # 清除当前行
    sys.stdout.write('\r')

    # 打印进度条、完成情况、执行时间和预计剩余时间
    sys.stdout.write(f"进度: [{'#' * hash_count}{'-' * (bar_length - hash_count)}] "
                     f"{percent_complete * 100:.2f}% 完成 "
                     f"({completed_count}/{total_count}) "
                     f"执行时间: {elapsed_time:.2f}秒 "
                     f"预计剩余时间: {remaining_time:.2f}秒")
    sys.stdout.flush()


# 使用示例
total_count = 10000
start_time = time.time()

for i in range(total_count):
    time.sleep(0.001)  # 模拟任务执行时间
    display_progress(total_count, i + 1, start_time)

sys.stdout.write('\n')

代码解释:

  1. display_progress 函数定义了一个用于显示进度信息的函数,包括一个固定长度的进度条。
  2. 参数说明:
    • total_count:总数量
    • completed_count:已完成数量
    • start_time:开始执行时间
    • bar_length:进度条的长度,默认为50
  3. 函数内部逻辑:
    • 计算已完成的百分比。
    • 根据百分比计算进度条上显示的 ‘#’ 数量。
    • 计算已经过去的时间。
    • 如果已完成任务数量大于0,计算预计剩余时间;否则,剩余时间设为0。
    • 使用 sys.stdout.writesys.stdout.flush 在同一行中打印进度条、完成情况、执行时间和预计剩余时间。
  4. 使用示例:
    • 定义 total_countstart_time
    • 循环执行任务,每次执行后调用 display_progress 函数更新进度条。
    • 最后使用 sys.stdout.write 换行,确保输出信息的完整性。

使用该函数的好处:

  • 提供了一个简单而有效的方法来显示长时间运行任务的进度,使用户能够清晰地了解任务的完成情况和预计剩余时间。
  • 进度条的长度和显示格式可以根据需求进行定制。
  • 可以轻松地集成到各种 Python 项目中,提高了代码的可读性和用户体验。

解释代码 由GPT4.0 协助完成
贵有贵的道理 。。。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈钇谷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值