gpt4 book ai didi

python - 为什么此代码在 Python 3 中速度较慢?

转载 作者:太空狗 更新时间:2023-10-30 02:49:54 24 4
gpt4 key购买 nike

我刚写了这段代码,我想知道为什么它在 Python 3 中的表现明显更差?所有平台都一样吗?这只是运气不好,还是 Py3 通常比较慢?

谢谢!

性能:

       python 2.6  python 3.1  pypy 1.5
linux 2.2s 2.4s 0.8s
os x 2.5s 3.4s 0.7s

代码:(抱歉,太草率了,效率太低了!)

import itertools
import random

def fptp_draw(result):
votes = [prefs[0] for prefs in result]
counts = [len([v for v in votes if v == c]) for c in [1, 2, 3]]
s = sorted(counts)
#print('fptp', counts)
return s[-1] == s[-2]

def av_remove(prefs, cand):
if prefs[0] != cand:
return prefs
else:
return prefs[1:]

def av_draw(result):
nv = len(result)
cands = [1, 2, 3]
while True:
votes = [prefs[0] for prefs in result]
counts = [len([v for v in votes if v == c]) for c in cands]
#print('av ', cands, counts)
s = sorted(counts)

if s[-1]*2 > nv:
return False
if len(cands) == 2:
return True

loser = cands[counts.index(s[0])]
cands.remove(loser)

result = [av_remove(prefs, loser) for prefs in result]

return False

#orders = list(itertools.permutations([1, 2, 3]))
orders = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

#results = list(itertools.product(*itertools.repeat(orders, 6)))
#results = random.sample(results, 5)

def rand_vote():
return [random.choice(orders) for i in range(1000)]

n = fptp = av = 0
for j in range(1000):
r = rand_vote()
#print()
#print(r)
n += 1
if fptp_draw(r):
fptp += 1
if av_draw(r):
av += 1

print(fptp*100.0/n, av*100.0/n)
print(n)

最佳答案

Py3k一般是slower比 python 2.x。这会随着时间的推移而改变,但 py3k 的重点是功能的完整性和稳定性,而不是速度。

关于python - 为什么此代码在 Python 3 中速度较慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5915019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com