跟踪并显示已执行代码的百分比
我有一段非常大的代码,运行起来需要一些时间。为了确保这个过程没有卡住,我会在屏幕上打印出已经执行的代码百分比,这个百分比是根据一个for
循环和一个整数来计算的。
为了显示for
循环已经处理的百分比,我使用了一些标志来表示循环已经执行了多少。
下面的MWE
可能会让这个过程更清楚:
import time
N = 100
flag_15, flag_30, flag_45, flag_60, flag_75, flag_90 = False, False,\
False, False, False, False
for i in range(N):
# Large block of code.
time.sleep(0.1)
if i + 1 >= 0.15 * N and flag_15 is False:
print '15%'
flag_15 = True
elif i + 1 >= 0.3 * N and flag_30 is False:
print '30%'
flag_30 = True
elif i + 1 >= 0.45 * N and flag_45 is False:
print '45%'
flag_45 = True
elif i + 1 >= 0.6 * N and flag_60 is False:
print '60%'
flag_60 = True
elif i + 1 >= 0.75 * N and flag_75 is False:
print '75%'
flag_75 = True
elif i + 1 >= 0.9 * N and flag_90 is False:
print '90%'
flag_90 = True
elif i + 1 == N:
print '100%'
这个方法有效,但代码写得比较繁琐,看起来也不太美观。我在想有没有更好或者更漂亮的方法来实现这个功能。
5 个回答
0
只需要在Misha的回答中加一个"\r"就可以了:
import sys
import time
for i in range(100):
row = "="*i + ">"
sys.stdout.write("%s\r %d%%\r" %(row, i + 1))
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("\n")
输出结果是:
65%======================================================>
在colab.research.google.com上是这样工作的:
import sys
import time
for i in range(100):
row = "="*i + ">"
sys.stdout.write("\r %d%% %s " %( i + 1,row))
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("\n")
0
你不需要任何标志。你可以直接根据当前的i值来打印完成的内容。
for i in range(N):
# lots of code
print '{0}% completed.'.format((i+1)*100.0/N)
2
你可以结合使用 write() 和 flush() 来实现一个漂亮的进度条:
import sys
import time
for i in range(100):
row = "="*i + ">"
sys.stdout.write("%s\r%d%%" %(row, i + 1))
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("\n")
进度条的显示效果会像这样:
69%====================================================================>
3
我喜欢用取模运算来定期打印状态信息。
import time
N = 100
for i in range(N):
#do work here
if i % 15 == 0:
print "{}% complete".format(int(100 * i / N))
print "100% complete"
结果:
0% complete
15% complete
30% complete
45% complete
60% complete
75% complete
90% complete
100% complete
如果N的值不是100,而你想每15%打印一次,那你就得动态计算步长,而不是直接用数字15
。
import time
import math
N = 300
percentage_step = 15
stride = N * percentage_step / 100
for i in range(N):
#do work
if i % stride == 0:
print "{}% complete".format(int(100 * i / N))
2
(我再发一个答案,因为这个解决方案用的是完全不同的方法)
你可以创建一个里程碑值的列表,当完成的百分比达到最低值时,就打印一条消息。
milestones = [15, 30, 45, 60, 75, 90, 100]
for i in range(N):
#do work here
percentage_complete = (100.0 * (i+1) / N)
while len(milestones) > 0 and percentage_complete >= milestones[0]:
print "{}% complete".format(milestones[0])
#remove that milestone from the list
milestones = milestones[1:]
结果:
15% complete
30% complete
45% complete
60% complete
75% complete
90% complete
100% complete
跟我之前提到的“步幅”方法不同,这里你可以精确控制打印哪些百分比。它们不需要均匀分布,也不需要能被N整除,甚至不需要是整数!如果你想的话,可以用 milestones = [math.pi, 4.8, 15.16, 23.42, 99]
。