gpt4 book ai didi

python - 为什么 Pypy 的双端队列这么慢?

转载 作者:太空狗 更新时间:2023-10-29 17:43:30 25 4
gpt4 key购买 nike

这是对 Project Euler Problem 49 的一次(有点乱)尝试.

我应该直截了本地说 deque 不是一个好的选择!我的想法是缩小素数集以测试成员资格会导致循环加速。然而,当我意识到我应该使用 set(而不用担心删除元素)时,我得到了 60 倍的加速。

from collections import deque
from itertools import permutations
from .sieve import sieve_of_erastothenes # my own implementation of the Sieve of Erastothenes

primes = deque(prime for prime in sieve_of_erastothenes(10000) if prime > 1000 and prime != 1487) # all four-digit primes except 1487
try:
while True:
prime = primes.popleft() # decrease the length of primes each time to speed up membership test
for inc in xrange(1,10000 + 1 - (2 * prime)): # this limit ensures we don't end up with results > 10000
inc1 = prime + inc
inc2 = prime + 2*inc

if inc1 in primes and inc2 in primes:
primestr = str(prime)
perms = set(''.join(tup) for tup in permutations(primestr)) # because permutations() returns tuples
inc1str = str(inc1)
inc2str = str(inc2)
if inc1str in perms and inc2str in perms:
print primestr + inc1str + inc2str
raise IOError # I chose IOError because it's unlikely to be raised
# by anything else in the block. Exceptions are an easy
# way to break out of nested loops.
except IOError:
pass

无论如何,在我想到使用 set 之前,我在 Pypy 中尝试过。我发现结果相当令人惊讶:

$ time python "problem49-deque.py"
296962999629

real 1m3.429s
user 0m49.779s
sys 0m0.335s

$ time pypy-c "problem49-deque.py"
296962999629

real 5m52.736s
user 5m15.608s
sys 0m1.509s

为什么 Pypy 在这段代码上慢了五倍以上?我猜 Pypy 版本的 deque 是罪魁祸首(因为它在 set 版本上运行得更快),但我不知道为什么会这样。

最佳答案

慢的部分是inc1 in primes and inc2 in primes。我会看看为什么 PyPy 这么慢(基本上感谢性能错误报告)。请注意,正如您提到的那样,代码可以变得非常快(在 PyPy 和 CPython 上)---在这种情况下,只需将 primes 双端队列复制到 for 之前的集合中 循环。

关于python - 为什么 Pypy 的双端队列这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13421326/

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