How to write Inline Functions in Python?
Michael Stenner
mstenner at phy.duke.edu
Thu Nov 14 09:50:38 EST 2002
On Thu, Nov 14, 2002 at 05:20:40PM +1100, Delaney, Timothy wrote:
> > From: arivu at qmaxtest.com [mailto:arivu at qmaxtest.com]
> > Is Inline Functions available in python?
>
> No.
>
> I assume you're coming from C++. In that case, I suggest you take a good
> hard look at why you want to write inline functions/methods anyway. If
> you're doing it for performance reasons, your compiler is almost certainly
> going to be better at deciding what to inline, and has the option to do so
> unless you explicitly tell it not to. If you're doing for any other reason
> (such as putting code in header files) I strongly advise against it.
>
> Inline was developed when computers were slower and compilers were more
> stupid. These days I see no need to inline whatsoever.
OK, I'm sincerely curious here and not trying to be argumentative. I
present the following example. I admit that it's a bit extreme, but
still:
==============================================================
#!/usr/bin/python2
N = 10000
def times_two(x):
return 2 * x
def via_function():
for i in range(N):
y = times_two(i)
def inline():
for i in range(N):
y = 2 * i
def run():
inline()
via_function()
import profile
profile.run('run()')
==============================================================
with the following results:
ncalls tottime percall cumtime percall
filename:lineno(function)
1 0.000 0.000 0.220 0.220 <string>:1(?)
0 0.000 0.000 profile:0(profiler)
1 0.020 0.020 0.240 0.240 profile:0(run())
1 0.010 0.010 0.010 0.010 py-inline.py:12(inline)
1 0.000 0.000 0.220 0.220 py-inline.py:16(run)
10000 0.050 0.000 0.050 0.000 py-inline.py:5(times_two)
1 0.160 0.160 0.210 0.210 py-inline.py:8(via_function)
There's a resolution issue here, sometimes inline takes 0.020 rather
than 0.010, but conservatively, the "inline" version is 10 times
faster. Now, how much of a problem this is in real live programs is
debatable. I've often wished for an inline function for reasons that
are not too far from this.
-Michael
--
Michael Stenner Office Phone: 919-660-2513
Duke University, Dept. of Physics mstenner at phy.duke.edu
Box 90305, Durham N.C. 27708-0305
More information about the Python-list
mailing list