Basic Python Questions - Oct. 31, 2013

Skip Montanaro skip at pobox.com
Thu Oct 31 12:14:01 EDT 2013


> 1.  How fast can Python do math calculations compared with other languages
> such as Fortran and fast versions of Basic.  I would have to believe that it
> is much faster than Perl for doing math calculations.

As others have indicated, a lot depends on the form of your
calculations. There is a cost to crossing the Python/C boundary, and
you may or may not care about the other stuff Python can do
on-the-fly, like promote ints to Python longs, check for zero
division, etc. If you have floating point code that is array-like,
then organizing it to use numpy can be a big win, as you will cross
that expensive boundary much less often per underlying operation. (I'm
thinking here of more complex operations like trigonometric functions,
not simple adds and subtracts, which are handled by the Python virtual
machine.)

I will relate one anecdote from my job here which highlights the cost
of the boundary. I work at a trading firm. I work solely within a
Python world, but my stuff is built on top of a lot of C++ code
developed by others at the firm. Several years ago, it was decided
that we needed a price library because some exchanges (the London
Stock Exchange, for example) sets the minimum price change based on
the current trading price range. Consider a stock like AAPL, which
closed yesterday at 489.56. It trades in pennies on NASDAQ, no matter
its price. If it was on the LSE, it might trade in half pennies if it
was trading in a $100 range, or in dimes if it was trading near $1000
range. (I'm making this stuff up, just to give you an idea what I'm
referring to.)

So, a price library was written in C++. You could ask for the next
higher or lower valid price. It was all very peppy, because of course,
it relied heavily on C++ inline functions for all these simple
operations. It was wrapped with Boost::Python and tossed over the
fence for us Python peons to use. Guess what? It was unbearably slow,
because not only did we were crossing the Python/C boundary to do
little more (most of the time) than a single add or subtract.

The solution was to write a pure Python version of the parts that mattered most.

Moral of the story: consider how your code is structured and whether
it makes sense to reorganize it when implementing in Python.

Skip



More information about the Python-list mailing list