1

私は、本来あるべきよりもはるかに遅い 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(ボトルネックはetc... 行にあると確信しています。私はここで推測していますが、辞書内のすべてのエントリを検索し、どのエントリが正しいキーを持っているかを確認することで、辞書が機能すると想定しています。繰り返しになりますが、リストはエントリ番号から派生したメモリ位置で情報を読み取るだけであり、非常に大きな (正確には 200,000 エントリ) リスト/ディクテーションははるかに高速です。

dict のエントリをリストに変換すると、このコードが高速になりますか? これを行うにはどうすればよいですか(ドキュメントを今見直して、そのための機能を見たと思いました...)?これをより速くするために誰かが気付く他の方法はありますか?

4

3 に答える 3

4

ループを通過するたびにリストを作成していますが、そのリストは変更されていません。ループの外側に移動します。

starlist=list(stardict.keys())
...
    theplanet.star=stardict[random.choice(starlist)]     #Choose a random star

問題はほぼ確実にdictルックアップにはありません。それらは非常に高速なハッシュテーブルに基づいています。

于 2013-03-04T17:35:43.547 に答える
2
  1. リスト生成list(stardict.keys())をループ外に移動する

  2. コードのプロファイリングを試みます (ドキュメント)

  3. CPython を実行していると仮定して、コードがPypyで実行できるかどうかを確認してください。これにより、最適化された JIT により、パフォーマンスが向上する可能性があります。

于 2013-03-04T17:45:00.780 に答える
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.")
于 2013-03-04T18:00:04.470 に答える