Skip to content

Instantly share code, notes, and snippets.

@h3ik0th
Created October 15, 2021 15:50
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 h3ik0th/504ba86b4aa9fabd70a4df556f8ebdd1 to your computer and use it in GitHub Desktop.
Save h3ik0th/504ba86b4aa9fabd70a4df556f8ebdd1 to your computer and use it in GitHub Desktop.
# list comprehension to square each number in a LARGE list of 100,000 numbers
rands = [random.randrange(1, 100, 1) for i in range(100000)]
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>
rands2 = []
for n in rands:
n = n**2
rands2.append(n)
# >>>>>>>>>>>>>>>>>>>>>>>>
tLoop = time.perf_counter() - t
print(f'{tLoop:.3f} sec')
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
_ = [n**2 for n in rands]
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
tComp = time.perf_counter() - t
print(f'{tComp:.3f} sec: comprehension vs loop: {100*(tComp/tLoop-1):.1f}%')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment