我有一个非常大的代码,需要一些时间才能运行。为了确保进程没有在某处停止,我打印以筛选已执行代码的百分比,这取决于 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%'
这行得通,但非常冗长且非常丑陋。我想知道是否有更好/更漂亮的方法来做到这一点。
最佳答案
我喜欢使用模数来定期打印状态消息。
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
对于 100 以外的 N 值,如果您想每 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))
关于python - 跟踪和显示已执行代码的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22252859/