這是在Project Euler Problem 49(稍微凌亂)的嘗試。Pypy爲什麼這麼慢?
我應該說徹底的認爲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。我發現結果是相當suprising:
$ 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
版本上運行得更快),但我不知道這是什麼原因。
感謝您提出這個問題!我正要發佈一個問題,詢問爲什麼我的代碼版本比列表版本慢28%。 –