Skip to content

Instantly share code, notes, and snippets.

@tanjuntao
Created May 1, 2020 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanjuntao/edad2133a5fc3214ac0d6aa2b82705f3 to your computer and use it in GitHub Desktop.
Save tanjuntao/edad2133a5fc3214ac0d6aa2b82705f3 to your computer and use it in GitHub Desktop.
python training progress bar
import time
import os
import sys
term_width = 148
TOTAL_BAR_LENGTH = 65.
last_time = time.time()
begin_time = last_time
def progress_bar(current, total, msg=None):
global last_time, begin_time
if current == 0:
begin_time = time.time()
cur_len = int(TOTAL_BAR_LENGTH * current / total)
rest_len = int(TOTAL_BAR_LENGTH - current)- 1
sys.stdout.write('[')
for i in range(cur_len):
sys.stdout.write('=')
sys.stdout.write('>')
for i in range(rest_len):
sys.stdout.write('.')
sys.stdout.write(']')
cur_time = time.time()
step_time = cur_time - last_time # 每一步的计算时间
last_time = cur_time
tot_time = cur_time - begin_time # 总共的计算时间
L = []
L.append(' Step: %s' % format_time(step_time))
L.append(' | Tot: %s' % format_time(tot_time))
if mag:
L.append(' | ' + msg)
msg = ''.join(L)
sys.stdout.write(msg)
# 剩下的部分写入空格
for i in range(term_width - int(TOTAL_BAR_LENGTH) - len(msg) - 3):
sys.stdout.write(' ')
# 移动光标到 progress bar 的中央
for i in range(term_width - (TOTAL_BAR_LENGTH / 2) + 2):
sys.stdout.write('\b')
# 写入当前进度
sys.stdout.write(' %d/%d ' % (current+1, total))
# 如果当前的 current 值还没有达到 total,那么将当前光标移动到行首
# 本次 progress_bar 调用结束
# 下一次,main 程序中将会传递个新的 current 值,重新调用 progrss_bar,还是在当前行显示进度
# 如果 current 已经到达 total 值,那么将会换行,下一次 main 中调用时,就会在新行显示进度
if current < total - 1:
sys.stdout.write('\r')
else:
sys.stdout.write('\n')
# 每轮调用结束需要在控制台中刷新
sys.stdout.flush()
def format_time(seconds):
days = int(seconds / 3600/24)
seconds = seconds - days*3600*24
hours = int(seconds / 3600)
seconds = seconds - hours*3600
minutes = int(seconds / 60)
seconds = seconds - minutes*60
secondsf = int(seconds)
seconds = seconds - secondsf
millis = int(seconds*1000)
f = ''
i = 1
if days > 0:
f += str(days) + 'D'
i += 1
if hours > 0 and i <= 2:
f += str(hours) + 'h'
i += 1
if minutes > 0 and i <= 2:
f += str(minutes) + 'm'
i += 1
if secondsf > 0 and i <= 2:
f += str(secondsf) + 's'
i += 1
if millis > 0 and i <= 2:
f += str(millis) + 'ms'
i += 1
if f == '':
f = '0ms'
return f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment