1

I'd like to understand why I get the speed differences that I see when I compose functions in different ways. I'm mostly interested in understanding why case (1) is faster than case (2).

Thanks!

import math
from time import time

def f(x):
    return 2*x
def g(x):
    return x*x
def h(x):
    return math.sqrt(x)

time0 = time()
for x in range(1,10**7):
    x_ = h(g(f(x)))
print 'h(g(f(x))): {}'.format( time() - time0)

def fgh(x):
    return h(g(f(x)))
time0 = time()
for x in range(1,10**7):
    x_ = fgh(x)
print 'composed: {}'.format( time() - time0)

time0 = time()
for x in range(1,10**7):
    x_ = f(x)
    x__ = g(x_)
    x___ = h(x__)
print 'subsequent: {}'.format( time() - time0)

As runtimes, I get:

h(g(f(x))): 2.83475399017
composed: 3.29999113083
subsequent: 3.4387819767

1 Answer 1

1

For starters, case 2 has one extra call - that of fgh(x), whereas in case 1 you're calling h(g(f(x))) directly. Inside a tight loop that gets executed many times, that additional function call can add extra execution time. Case 1 in-lines that call, so it's a bit faster. Case 3 is doing some extra assignments and loading variables, which explains why it's slower.

Sign up to request clarification or add additional context in comments.

2 Comments

OK, I thought something like that. Is it fair to say that if each of the composed functions is more complex and time intensive, it doesn't matter for the runtime how I compose them? (i.e. the additional function call in example 2 becomes negligible)
For the general case, it depends on the function - there might be situations where the composition order does matter (for instance: when composing the multiplication of large matrices). For your example it might not matter that much, but one can assume that operations such as taking the square root will be slower for larger numbers, so it'll be slightly slower if we leave it for the end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.