Created
February 20, 2022 17:05
-
-
Save mikeckennedy/2ddb5ad84d6e116e6d14b5c2eef4245a to your computer and use it in GitHub Desktop.
Are list comprehensions faster than loops?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
count = 10_000_000 | |
def with_loop(): | |
lst = [] | |
for n in range(1, count): | |
if n % 2 == 0: | |
lst.append(n) | |
return lst | |
def with_comp(): | |
return [n for n in range(1, count) if n % 2 == 0] | |
def time(func, name): | |
t0 = datetime.datetime.now() | |
func() | |
t1 = datetime.datetime.now() | |
ms = (t1 - t0).total_seconds() * 1000 | |
print(f"{name} done in {ms:.3f} ms") | |
with_loop() | |
with_comp() | |
time(with_loop, "loop") | |
time(with_comp, "comp") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, on my mac I get: