Skip to content

Instantly share code, notes, and snippets.

@colematt
Created March 12, 2020 22:11
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 colematt/a7f14ad5d74b1e80254ca85faada2dd7 to your computer and use it in GitHub Desktop.
Save colematt/a7f14ad5d74b1e80254ca85faada2dd7 to your computer and use it in GitHub Desktop.
Using reduce and lambda isn't faster than built-in max!
#!/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