Supamee
Supamee

Reputation: 635

Why is an Imported Function Slower in Python

I tried restructuring my code to have a function defined in another file and noticed it seems to be running a bit slower. I'm wondering if anyone knows how to prevent this slowdown or if there is a known reason for this. I had understood imports in python to be the same as copy-pasting your code so this slow down is strange to me.

An example:

from datetime import datetime
from import_test import small_test_import

def small_test(x):
    return x+1

start1 = datetime.now()
for i in range(x):
    Z=small_test(1)
end1 = datetime.now()
print(end1-start1) #1.355964

start2 = datetime.now()
for i in range(x):
    Z=small_test_import(1)
end2 = datetime.now()
print(end2-start2) #1.433045

or to use timeit:

def wrapper(func, *args, **kwargs):
    def wrapped():
         return func(*args, **kwargs)
    return wrapped

wrapped = wrapper(small_test, 1)
print(timeit.timeit(wrapped,number=x)) #1.8407
wrapped = wrapper(small_test_imported, 1)
print(timeit.timeit(wrapped, number=x)) #2.1006

I realize this isn't a huge time difference but it is consistent.

Upvotes: 0

Views: 1043

Answers (1)

stackeks
stackeks

Reputation: 66

The time diffs you are printing in your script show a difference of around 0.8 seconds, if I'm not mistaken? The imported function is most probably not slower, but your test setup gives it a disadvantage: it has to clean up the existing Z object. Your script re-uses the variable Z and therefore, the second for-loop has to clean up the object (the returned value) you bound to Z in the first test.

Try the measurement again with this code:

start1 = datetime.now()
for i in range(x):
    X = small_test(1)
end1 = datetime.now()
print(end1-start1)

start2 = datetime.now()
for i in range(x):
    Y = small_test_import(1)
end2 = datetime.now()
print(end2-start2)

It should not produce a notable difference.

Upvotes: 1

Related Questions