Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.