Is it true that Python code is faster in a function?

I saw a comment that led me to the question Why is Python code faster in a function? .

I thought and thought that I would try it myself using the timeit library, but I got very different results:

( note : 10**8 was changed to 10**7 to make things a little faster)

 >>> from timeit import repeat >>> setup = """ def main(): for i in xrange(10**7): pass """ >>> stmt = """ for i in xrange(10**7): pass """ >>> min(repeat('main()', setup, repeat=7, number=10)) 1.4399558753975725 >>> min(repeat(stmt, repeat=7, number=10)) 1.4410973942722194 >>> 1.4410973942722194 / 1.4399558753975725 1.000792745732109 
  • Did I use timeit ?
  • Why are these results less than 0.1% different from each other, while the results on another issue were almost 250% different?
  • Does it matter only when using CPython compiled versions of Python (like Cython)?
  • Ultimately: Is Python code really faster faster, or does it depend only on how you use it?
+7
source share
2 answers

The disadvantage of your test is the timeit way timeit compile your stmt code. It is really compiled in the following template:

 template = """ def inner(_it, _timer): %(setup)s _t0 = _timer() for _i in _it: %(stmt)s _t1 = _timer() return _t1 - _t0 """ 

Thus, stmt actually works in a function using the fastlocals array (i.e. STORE_FAST ).

Here's a test with your function in question like f_opt compared to the unoptimized compiled stmt executed in f_no_opt function:

 >>> code = compile(stmt, '<string>', 'exec') >>> f_no_opt = types.FunctionType(code, globals()) >>> t_no_opt = min(timeit.repeat(f_no_opt, repeat=10, number=10)) >>> t_opt = min(timeit.repeat(f_opt, repeat=10, number=10)) >>> t_opt / t_no_opt 0.4931101445632647 
+10
source

It comes down to compiler optimization algorithms. When compiling β€œjust in time” it is much easier to identify frequently used code fragments if they are in functions.

Efficiency will really depend on the nature of the tasks performed. In the example you gave, you are not really doing anything computationally intensive, leaving less room for efficiency through optimization.

As others have noted, CPython does not compile on time. However, when compiling code, C compilers will often execute them faster.

Check out this document in the GCC compiler: http://gcc.gnu.org/onlinedocs/gcc/Inline.html

+1
source

All Articles