带刷新的文本进度条引出的Pytho3.8废除time.clock()方法的取代方法

问题起因

在学习Python语言程序设计基础中3.7.3的带刷新的文本进度条时,发现time.clock的方法无法使用。提示:AttributeError: module ‘time’ has no attribute ‘clock’。经过查询发现time.clock()在Python3.8中已经废除。
clock错误截图

import time
scale=50
print("执行开始".center(scale//2,'-'))
t=time.clock()
for i in range(scale+1):
    a='*'*i
    b='.'*(scale-i)
    c=(i/scale)*100
    t-=time.clock()
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),\
          end='')
    time.sleep(0.05)
print("\n"+"执行结束".center(scale//2,'-'))

替代方法

经过查找发现有两种方法

1.time.perf_counter()
2. time.process_time()

这两种方法的区别在于是否计算time.sleep()中的时间

import time
t0=time.process_time()
time.sleep(1)
t1=time.process_time()
print(t1-t0)#=0.0
t2=time.perf_counter()
time.sleep(1)
t3=time.perf_counter()
print(t3-t2)#=1.0002965000000001

经过测试,方法一perf_counter()计算sleep()的值,方法二process_time()不计算。

问题解决

结合该题,题中使用了sleep()方法,所以我们采用方法一。

import time
scale=50
print("执行开始".center(scale//2,'-'))
t=time.perf_counter()
for i in range(scale+1):
    a='*'*i
    b='.'*(scale-i)
    c=(i/scale)*100
    t-=time.perf_counter()
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),\
          end='')
    time.sleep(0.05)
print("\n"+"执行结束".center(scale//2,'-'))

结果如下TextProgressBar
同书上一致,问题解决。
如想进一步了解这两种方法可参考[https://blog.csdn.net/qq_27283619/article/details/89280974]
给个三连吧

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AQ_No_Happy

你的满意是我的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值