我开发了以下Python代码来解决Project Euler problem #187,该代码可以正常运行,但平均每次运行大约11秒。 generatePrimes
对奇数运行Sieve of Eratosthenes并返回所有素数(不包括2
)
from utilities import generatePrimes
from time import perf_counter_ns
limit = 100000000
start = perf_counter_ns()
primes = generatePrimes(limit // 2)
answer = len(primes) + 1
for p in primes:
for q in primes:
if q > p or p * q >= limit:
break
answer += 1
end = perf_counter_ns()
print("Answer: {}".format(answer))
print("Calculated in {} seconds".format((end - start) / 1000000000))
在计划对其进行优化之前,我决定将其移至一个函数以使代码更清晰,如下所示。请注意,代码几乎完全相同,并已调整为在函数中。
from utilities import generatePrimes
from time import perf_counter_ns
def solve(limit: int):
primes = generatePrimes(limit // 2)
total = len(primes) + 1
for p in primes:
for q in primes:
if q > p or p * q >= limit:
break
total += 1
return total
start = perf_counter_ns()
answer = solve(100000000)
end = perf_counter_ns()
print("Answer: {}".format(answer))
print("Calculated in {} seconds".format((end - start) / 1000000000))
但是,现在平均运行时间为 9 秒。在函数定义之前放置start
的初始化对时间没有明显影响。 为什么将此代码放在函数中会导致更好的性能?