I have a hypothesis, but I'm not entirely sure of it. Here's what I tried:
from time import time
from random import random
factor = 100
def lesser(a,b):
if a < b:
return a
return b
if __name__ == "__main__":
start = time()
for _ in range(10000000):
a = random() * factor
b = random() * factor
l = lesser(a,b)
end = time()
print(end-start)
start = time()
for _ in range(10000000):
a = random() * factor
b = random() * factor
l = min(a,b)
end = time()
print(end-start)
When I run this on my laptop I get:
5.072136402130127
7.319249391555786
So what explains this? The lookup for the function call? I don't know, because mine is a function too. Is the global vs local really that different?
But here's an idea. The python min
function does something more than mine: It takes an arbitrary number of arguments. Look at the code for the python builtin function. It's on line 1915 and it immediately calls a more general function for both max and min on line 1796. That function has alot more going on than my short one. Maybe that stuff takes longer.
max()
function):https://pylint.pycqa.org/en/latest/user_guide/messages/refactor/consider-using-max-builtin.html
– Tracitracietime.time()
. E.g.timeit.timeit('if 1>2: pass')
vstimeit.timeit('max(1,2)')
. – Tracitracie