Created
March 12, 2020 22:11
-
-
Save colematt/a7f14ad5d74b1e80254ca85faada2dd7 to your computer and use it in GitHub Desktop.
Using reduce and lambda isn't faster than built-in max!
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 | |
import random | |
import functools | |
import timeit | |
# Construct a large list of integers with few repeats expected | |
random.seed() | |
randints = [random.randint(0,100000000) for _ in range(1000000)] | |
# Callable wrappers to the code in question | |
def reducemax(): | |
return functools.reduce(lambda x,y: x if x>y else y, randints) | |
def builtinmax(): | |
return max(randints) | |
# Time each callable, with 10 iterations each. | |
# Output is average time in seconds per iteration | |
print(timeit.timeit(reducemax,number=10)) | |
print(timeit.timeit(builtinmax,number=10)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment