Skip to content

Instantly share code, notes, and snippets.

@whistler
Created February 21, 2017 21:31
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 whistler/73d7bcf820041ccf64f902ceb38f0ee4 to your computer and use it in GitHub Desktop.
Save whistler/73d7bcf820041ccf64f902ceb38f0ee4 to your computer and use it in GitHub Desktop.
Benchmark loops vs list comprehension
N = 10000000
def loops():
nums = []
for num in range(N):
nums.append(num*2)
#print nums
def list_comprehensions():
nums = [num * 2 for num in range(N)]
#print nums
def benchmark(func):
import time
start = time.time()
func()
end = time.time()
name = func.__name__
seconds = end - start
print "FUNCTION: " + name + " TIME: " + str(seconds) + " s"
benchmark(loops)
benchmark(list_comprehensions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment