Created
May 25, 2020 09:06
-
-
Save gynvael/9bf1f3a6c78f613190de8e17c8f81031 to your computer and use it in GitHub Desktop.
Removing elements from list based on condition benchmark
This file contains 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
#!/usr/bin/python3 | |
""" | |
Results: | |
--- Remove if number is evenly dividable by 2 | |
1.2708177 | |
1.2841774 | |
0.667672 | |
--- Remove if number is evenly dividable by 3 | |
1.3165607 | |
1.1905327999999997 | |
0.6251088999999999 | |
--- Remove if number is evenly dividable by 4 | |
1.2822456 | |
1.0946345 | |
0.6509212999999998 | |
""" | |
def test1(): | |
x = list(range(1000)) | |
y = list(filter(lambda a: a % 4 != 0, x)) | |
x.clear() | |
x.extend(y) | |
def test2(): | |
x = list(range(1000)) | |
for i, item in enumerate(x): | |
if item % 4 == 0: | |
x.pop(i) | |
def test3(): | |
x = list(range(1000)) | |
y = [a for a in x if a % 4 == 0] | |
x.clear() | |
x.extend(y) | |
if __name__ == '__main__': | |
import timeit | |
print(timeit.timeit("test1()", setup="from __main__ import test1", number=10000)) | |
print(timeit.timeit("test2()", setup="from __main__ import test2", number=10000)) | |
print(timeit.timeit("test3()", setup="from __main__ import test3", number=10000)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment