如何估算一个for循环的迭代时间并以tqdm显示?

问题描述 投票:0回答:1

我想估算以下代码的迭代时间,并将其显示在进度条上(tdqm)。这个函数将给出所有可能的组合,其中的 string.printable.


import strings
from itertools import combinations

def generate_combinations(iterable):
  lst = list(iterable)
  for lenght in range(0, len(lst) + 1):
    for i in combinations(lst, lenght):
      with open('passwords.txt', 'a') as f:
        w = ''.join(map(str, i))
        f.write(w + '\n')

generate_combinations(string.printable)

我想你可以用 timetqdm.

预期的输出。

estimated time: 12 seconds left
tqdm progress bar: 12% |||||||...
python time itertools tqdm
1个回答
0
投票

最后的答案(与@jq170727的建议)是下面的代码。


import string
from tqdm.auto import trange, tqdm
from itertools import permutations

所要求的生成器(在google colab上,使用TPU:大约10k左右)。

def combined(lst, lenStart, lenEnd):
  for i in trange(lenStart, lenEnd + 1, desc='Progress'):
    for subset in tqdm(permutations(lst, i),  desc='Subsets', leave = False):
      w = ''.join(map(str, subset))
      yield w

在这里,我们得到了同样的发电机与更好的效率(在谷歌colab,使用TPU:约950k秒

def compress_permutation(lst, lenStart, lenEnd):
  yield ','.join([''.join(map(str, subset)) for i in trange(lenStart, lenEnd + 1, desc='Progress') for subset in tqdm(permutations(lst, i), desc='Subsets', leave = False)])
iterable = list(string.printable[:94])
lenStart, lendEnd = 1, 9

for subset in compress_permutation(iterable, l1, l2):
  with open('passwords.txt', 'a') as f:
    f.write(subset)
© www.soinside.com 2019 - 2024. All rights reserved.