Skip to content

Instantly share code, notes, and snippets.

@PM2Ring
Created June 4, 2017 21:47
Show Gist options
  • Save PM2Ring/ea746db64ecd17c2fb5d6907342f9911 to your computer and use it in GitHub Desktop.
Save PM2Ring/ea746db64ecd17c2fb5d6907342f9911 to your computer and use it in GitHub Desktop.
Compare the speed of sum(xrange()) to sum(range())
#!/usr/bin/env python
""" Compare the speed of sum(xrange()) to sum(range())
Written by PM 2Ring 2017.06.05
"""
from timeit import Timer
cmds = {
'range': 'sum(range(1, n+1))',
'xrange': 'sum(xrange(1, n+1))',
}
loops = 20000
setup = 'from __main__ import n'
for n in range(1, 20):
print n
timings = []
for name, cmd in cmds.items():
t = Timer(cmd, setup)
result = sorted(t.repeat(3, loops))
timings.append((result, name))
timings.sort()
for result, name in timings:
print '%-6s : %s' % (name, result)
print timings[0][0][0] / timings[1][0][0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment