Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Speed test.
import timeit
setup = """
def primes(n):
'''Get all primes up to n.'''
if n < 2:
return []
nums = range(n)
sieve = set(xrange(2, n))
for num in nums[2:int(n ** 0.5) + 1]:
if num in sieve:
sieve -= set(nums[num**2::num])
return sieve
"""
setup2 = """
def primes(n):
'''Get all primes up to n.'''
n = int(n)
if n < 2:
return []
sieve = range(n)
sieve[1] = 0
root = n ** 0.5
index = 0
while index <= root:
if sieve[index]:
i = index ** 2
while i < n:
sieve[i] = 0
i += index
index += 1
return [x for x in sieve if x]
"""
setup3 = """
def primes(n):
'''Get all primes up to n.'''
if n < 2:
return []
nums = tuple(xrange(n))
sieve = set(xrange(2, n))
for num in nums[2:int(n ** 0.5) + 1]:
if num in sieve:
sieve -= set(nums[num**2::num])
return sieve
"""
test = "primes(2000)"
print min(timeit.Timer(test, setup=setup3).repeat(7, 1000))
print min(timeit.Timer(test, setup=setup).repeat(7, 1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.