0

免责声明(稍后添加):我已修改代码以考虑下面的@jasonharper 和@user2357112supportsMonica 评论。仍然有内存问题。

我正在运行以下代码:

import itertools
from tqdm import tnrange
import random

def perm_generator(comb1, comb2):
    seen = set()
    length1 = len(comb1)
    length2 = len(comb2)
    while True:
        perm1 = tuple(random.sample(comb1, length1))
        perm2 = tuple(random.sample(comb2, length2))
        perm_pair = perm1 + perm2
        if ( (perm_pair not in seen) ):
            seen.add(perm_pair)
            yield [perm1,perm2]            


seq_all = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V') 
combinations_first_half = list(itertools.combinations(seq_all, int(len(seq_all)/2)))

n = 1000
random.seed(0)
all_rand_permutations = []
for i in tnrange(len(combinations_first_half), desc = 'rand_permutations'):
    comb1 = combinations_first_half[i]
    comb2 = tuple(set(seq_all) - set(comb1))
    gen = perm_generator(comb1,comb2)
    rand_permutations = [next(gen) for _ in range(n)]
    all_rand_permutations += rand_permutations

对于 for 循环的几乎所有迭代,一切都很顺利,每秒大约 33 次迭代。

但是,在极少数情况下,循环会卡住并开始在相当长的几秒钟内建立内存压力。最终,在给定的后续迭代中,内核死亡。

这似乎与random.sample()因为如果我从相对于内核死亡的迭代或高内存压力迭代之一的索引开始循环(因此,以某种方式因此移动random.seed()),没有问题并且循环通过就像其他快速迭代一样。

我在这里附上一些截图:

迭代构建高内存压力

迭代没有问题

内核死亡的迭代

4

0 回答 0