Created
May 29, 2013 07:06
-
-
Save Ceasar/5668460 to your computer and use it in GitHub Desktop.
Speed test!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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[: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] | |
""" | |
print min(timeit.Timer('primes(2000)', setup=setup).repeat(7, 1000)) | |
print min(timeit.Timer('primes(2000)', setup=setup2).repeat(7, 1000)) | |
# 0.27396607399 | |
# 0.482172966003 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment