我有一些Python代码远远超过实际应用的代码。
#Generate planets
for t in range(stars*3): #There are 3 planets for every star, but not every star will have 3 planets
theplanet=Planet()
if random.randint(0,100) <= 25: #25% of planets have life
theplanet.tl=random.randint(1,9) #With a random tech level
else:
theplanet.tl=0 #The rest don't
theplanet.star=stardict[random.choice(list(stardict.keys()))] #Choose a random star
theplanet.star.planets+=(theplanet,) #Append the new planet to the star's list of planets
theplanet.name=theplanet.star.name+"-"+str(len(theplanet.star.planets)) #Name the planet Starname-X, where X is the length of the star's planets tuple. Since this increases every time a planet is added, it will be 1 for the first planet, 2 for the next, etc...
if math.floor((t/(stars*3))*100)==(t/(stars*3))*100: print("Generating planets: "+str((t/(stars*3))*100)+"% done.")
我非常确定瓶颈在star=stardict[random.choice(list(
等等......行。我在这里猜测,但我认为dicts通过搜索dict中的每个条目并查看哪个条目具有正确的密钥来工作。列表,我再次假设,只是读取从条目号导出的内存位置的信息,对于非常大的(200,000个条目,确切地说)列表/序列要快得多。
将dict的条目转换为列表会使这段代码更快吗?我该怎么做(我以为我看到了它的功能,现在回顾文档......)?有没有其他人注意到这个更快的方式?
答案 0 :(得分:4)
每次循环都会创建一个列表,但该列表是不变的。将它移到循环之外。
starlist=list(stardict.keys())
...
theplanet.star=stardict[random.choice(starlist)] #Choose a random star
问题几乎肯定不在dict查找中。它们基于非常快的哈希表。
答案 1 :(得分:2)
将列表生成list(stardict.keys())
移到循环外
尝试分析您的代码(documentation)
假设您正在运行CPython,请检查您的代码是否可以使用Pypy运行。由于其优化的JIT
答案 2 :(得分:0)
您只能使用中间值中的键来选择stardict中的随机项。您可以直接使用字典的值列表:
#Generate planets
starlist = stardict.values()
for t in range(stars*3): #There are 3 planets for every star, but not every star will have 3 planets
theplanet=Planet()
if random.randint(0,100) <= 25: #25% of planets have life
theplanet.tl=random.randint(1,9) #With a random tech level
else:
theplanet.tl=0 #The rest don't
theplanet.star=random.choice(starlist) #Choose a random star
theplanet.star.planets+=(theplanet,) #Append the new planet to the star's list of planets
theplanet.name=theplanet.star.name+"-"+str(len(theplanet.star.planets)) #Name the planet Starname-X, where X is the length of the star's planets tuple. Since this increases every time a planet is added, it will be 1 for the first planet, 2 for the next, etc...
if math.floor((t/(stars*3))*100)==(t/(stars*3))*100: print("Generating planets: "+str((t/(stars*3))*100)+"% done.")