为什么这段代码在 Python 3 中变慢了? [英] Why is this code slower in Python 3?

查看:60
本文介绍了为什么这段代码在 Python 3 中变慢了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I just wrote this code, and I was wondering why it performs significantly worse in Python 3? Is it the same across all platforms? Is this just bad luck, or is Py3 generally slower?

谢谢!

性能:

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

代码:(抱歉这么仓促和效率低下!)

Code: (sorry it's so hasty and inefficient!)

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 一般是 比 python 2.x 慢.这会随着时间的推移而改变,但 py3k 的重点是功能的完整性和稳定性,而不是速度.

Py3k is generally slower than python 2.x. That will change as time passes, but the focus for py3k was feature completeness and stability, not speed.

这篇关于为什么这段代码在 Python 3 中变慢了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆