Is Python really slow?

Ken Seehof 12klat at sightreader.com
Thu Jun 1 00:35:00 EDT 2000


Cedric Adjih wrote:

> Alexander <alecdem at mit.edu> wrote:
> > Michael Hudson wrote:
> >> Alexander <alecdem at mit.edu> writes:
> >>
> >> > Hi
> >> >
> >> > I have implemented  loop in Python
> >> >
> >> > for k in xrange(1,100000000):
> >> >    pass
> >> >
> >> > and the same one in  C
> >> > for ( i = 0 ; i < 1e8; i++ ) ;
> >> >
> >> > and the second one seems to be working hundreds of times faster than the
> >> > first one
> >> >
> >> > Can I do anything with that.
> >>
> >> Well, it's an empty loop so it's pretty useless to all mankind.
> >>
> >> Is this /just/ a troll, or has Python's (relative) lack of speed
> >> bothered you?  Yes, C can spin empty loops faster (especially if the
> >> optimiser removes the loop entirely...), but for doing most
> >> significant things, the difference is much less noticeable.
> >
> > Actually I've created array and did something like this :
> >
> > for k in xrange(1,10000):
> >   for m in range(1,10000):
> >     x[m] =  .... #some calculation of the value of an array's element x[m]
> >
> > and this work's realy slow compared to C. I don't mind it working 3 times
> > slower, but ..
> >
> > Perhaps it is possible, to do something like  implementing loops in C inside
> > Python ??
> > (though it seems to me it will not help)
>
>   You're right, Python is slow. That is fast to program with, but slow
> to run. For many cases, it is fast enough.
> For other cases, its speed is an issue, but programmer time is deemed
> more important.
> For other cases, one can profile, and write a C module (with the
> extension API, SWIG, CXX or SCXX), for the bottlenecks, when possible.
>
> If you need more speed than Python has (but not top speed), and something
> more clean than C++, you can try something in between, such
> as Java or Eiffel.
>
> -- Cedric

In practice (at least in my experience), it is very unusual for python to actually
be a bottleneck.  The reason is that most time is usually spent in library calls
written in C.  In those cases where a profile indicates that python code is a
bottleneck, I write a C module.  In just about all major software projects, only a
very small amount of code (as little as 1%-2%) eats up almost all of the CPU time,
and that is the part you will want to write in C.

When all is said and done, my python projects typically run faster than would have
if they had been written in C because my code is cleaner and my algorithms are
more clever when I write in python.  I spend a smaller portion of my time
debugging, and I don't avoid re-writing code that I don't like (in C or C++ it is
often hazardous to make any changes at all).

For me, the best balance is to write in python and use C or C++ as a slave
language.

- Ken Seehof





More information about the Python-list mailing list