Skip to content

Instantly share code, notes, and snippets.

@terriyu
Last active December 17, 2015 23:09
Show Gist options
  • Save terriyu/5687203 to your computer and use it in GitHub Desktop.
Save terriyu/5687203 to your computer and use it in GitHub Desktop.
Benchmarking different methods of running for loops
import pygame
pygame.init()
clock = pygame.time.Clock()
a = list(range(10000000))
def do_with_range():
clock.tick()
k = 0
for idx in range(len(a) - 1):
a[idx] < a[idx + 1]
print(clock.tick())
def do_with_xrange():
clock.tick()
k = 0
for idx in xrange(len(a) - 1):
a[idx] < a[idx + 1]
print(clock.tick())
def do_with_enumerate():
clock.tick()
prev_num = None
for idx, num in enumerate(a):
if prev_num is not None:
prev_num < num
prev_num = num
print(clock.tick())
>>> from benchmark import *
>>> do_with_range()
1492
>>> do_with_xrange()
977
>>> do_with_enumerate()
955
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment