Is there a way to combine two functions in python without the cost of calling two extra functions? For example, running:
from time import time
func1 = lambda x, y: x * y
func2 = lambda x, y: x + y
combinedFunc1 = lambda x, y: func1(x, y) * func2(x, y)
combinedFunc2 = lambda x, y: (x * y) * (x + y)
start = time()
for x, y in zip(range(10_000_000), range(10_000_000)):
temp = combinedFunc1(x, y)
print(f'Combined Function #1: {time() - start}')
start = time()
for x, y in zip(range(10_000_000), range(10_000_000)):
temp = combinedFunc2(x, y)
print(f'Combined Function #2: {time() - start}')
Results in:
'Combined Function #1: 3.116791248321533'
'Combined Function #2: 2.068246364593506'
combinedFunc1 is 50% slower due to the extra function calls (I'm assuming this is the reason). Is there a way to combine func1 and func2 in a way such as combinedFunc2 so as not to deal with the extra overhead of calling two more functions, for an unknown func and func2 (i.e. without knowing what func1 and func2 are calculating?)
Ideally I would like to combine an indeterminate number of functions, but I expect that knowing how to do so with two functions results in a way to do so with arbitrarily many.