Locked
Locked

Reputation: 61

Python difference between statement and function

I am currently using python to work with tons of data, and I got a bit curious... Since it's a lot of data, code speed really matters, so is there a difference between a few statements and a function that do so? is there a difference between

def my_function(var1):
    var2 = var1 + 1
    var3 = var1 - 1
    var4 = str(var1)
    print(var2, var3, var4)


for i in range(100000):
    my_function(i)

and

for i in range(100000):
    var1 = i
    var2 = var1 + 1
    var3 = var1 - 1
    var4 = str(var1)
    print(var2, var3, var4)

when talking about how fast the code is?

Upvotes: 1

Views: 243

Answers (2)

Wolph
Wolph

Reputation: 80021

It most likely won't have any measurable effect on your code, unless you're doing pretty much nothing inside the function.

To illustrate:

In [1]: def spam(eggs):
   ...:     pass
   ...:
   ...:

In [2]: def a():
   ...:     for i in range(1000000):
   ...:         spam(i)
   ...:

In [3]: def b():
   ...:     for i in range(1000000):
   ...:         pass
   ...:

In [4]: %timeit a()
104 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [5]: %timeit b()
25.9 ms ± 871 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

If, however, the code is actually doing something you won't really notice the difference anymore:

In [1]: def spam(eggs):
   ...:     return sum(x for x in range(eggs))
   ...:
   ...:

In [2]: def a():
   ...:     total = 0
   ...:     for i in range(1000):
   ...:         total += spam(i)
   ...:

In [3]: def b():
   ...:     total = 0
   ...:     for i in range(1000):
   ...:         total += sum(x for x in range(i))
   ...:

In [4]: %timeit a()
31 ms ± 1.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [5]: %timeit b()
31.8 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Also: Premature optimization is the root of all evil -- DonaldKnuth

Upvotes: 1

Yserbius
Yserbius

Reputation: 1414

When it's being interpreted there's a small difference, but it depends on the function size, how many times it's being called, what it's doing, etc.

For compiled Python code, the compiler is generally smart enough to "unwrap" functions into their component pieces for optimization.

Upvotes: 0

Related Questions