Friday, April 27, 2012

avoid using loops!

So one of the important things to know about python is that it is an "interpreted" language, not a compiled language.  Interpreted languages (like python, IDL, and Matlab) are designed to be "higher-level" languages, and thus do not have to be compiled in the same way as C or C++, for example.  This makes some things simpler, but there are some costs.

One of the costs is that loops take a long time to execute.  See the following example:


As you see, doing operations element-by-element on an array is MUCH slower than working with whole arrays at a time.  In fact, behind the scenes, numpy is using all the power of compiled code to make these array operations lightening-fast.  But you don't need to know how this works; all you need to do is get comfortable working with whole arrays, whenever possible.  A good example of this in action is the difference between the following two ways to create arrays of random numbers:


No comments:

Post a Comment