Created
December 8, 2015 13:47
-
-
Save anonymous/8b387decc6c27e81be82 to your computer and use it in GitHub Desktop.
Ritchie python benchmark
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
#!/usr/bin/env python | |
import time | |
from math import sqrt | |
class Timer(object): | |
'''Provides a timer context''' | |
def __enter__(self): | |
self.start = time.time() | |
return self | |
def __exit__(self, *args, **kwds): | |
self.end = time.time() | |
self.elapsed = self.end - self.start | |
print('Elapsed: {:>4.2} sec'.format(self.elapsed)) | |
def isPrime(n): | |
if (n < 2): | |
return False | |
elif (n == 2): | |
return True | |
elif (n % 2 == 0): | |
return False | |
upper_limit = int(sqrt(n)) | |
i = 3 | |
while (i <= upper_limit): | |
if (n % i == 0): | |
return False | |
i += 2 | |
return True | |
def main(): | |
lim = 2000000 | |
no_primes = 0 | |
n = 0 | |
with Timer() as t: | |
while (n <= lim): | |
if (isPrime(n)): | |
no_primes += 1 | |
n += 1 | |
print("Number of primes in the interval [0,%d]: %d" % (lim, no_primes)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment