relative speed of incremention syntaxes (or "i=i+1" VS "i+=1")

Christian Heimes lists at cheimes.de
Mon Aug 22 04:04:08 CEST 2011


Am 22.08.2011 01:25, schrieb Andreas Löscher:
> It's not as bad as you think. The addition of two integers is a cheap
> task (in terms of computation power). If you have two way's to to it,
> every little think (jumps in the code etc. ) will have a larger impact
> on the execution time than on an expensive operation.
> 
> But every improvement on your algorithm will easily result in a
> significant shorter execution time than replaceing a+=1 with a=a+1 will
> ever do. :-)

You can learn an important lesson here. Since Python is a high level
language without a JIT (yet) integer operations are much slower than in
C or other low level languages. In general it's not a problem for most
people. However if your algorithm is speed bound to integer operations
or has a tight inner for loop than you can gain a considerable amount of
speedup with C code. Reference counting and Python object creation need
several CPU cycles. Also a good algorithm and a modern C compiler can
make use of SIMD instructions, too.

If you ever feel the need to implement something fast e.g. an encryption
algorithm then you'd better off with a C implementation. Cython is my
favourite tool for the job.

Christian




More information about the Python-list mailing list