Skip to content

Instantly share code, notes, and snippets.

Created December 8, 2015 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/8b387decc6c27e81be82 to your computer and use it in GitHub Desktop.
Save anonymous/8b387decc6c27e81be82 to your computer and use it in GitHub Desktop.
Ritchie python benchmark
#!/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