Skip to content

Instantly share code, notes, and snippets.

@chaosmail
Created October 11, 2014 18:00
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 chaosmail/3e10235e607cebebb234 to your computer and use it in GitHub Desktop.
Save chaosmail/3e10235e607cebebb234 to your computer and use it in GitHub Desktop.
Check performance of loops and arrays in Python
from __future__ import print_function
import cProfile
import random
num_elems = 1000000
test = [random.randint(1,100) for i in range(num_elems)]
print("Loops\n*******")
print("Range and Len")
cProfile.run('[test[k] for k in range(len(test))]')
print("Enumerate")
cProfile.run('[test[k] for k,v in enumerate(test)]')
print("For")
cProfile.run('[v for v in test]')
print("Arrays\n*******")
some_value = "Test"
print("Append")
cProfile.run('for i in range(num_elems, 2*num_elems-1): test.append(some_value)')
print("Extend first")
cProfile.run('test.extend([]*num_elems)\nfor i in range(num_elems, 2*num_elems-1): test[i] = some_value')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment