Primitive root mod p

Transire suum pectus mundoque potiri

Python Hacking 7 January, 2008

Filed under: Programming — Nikolas Karalis @ 5:43 am

Efficiency Tips

In this post, i will try to collect tips and tricks for efficient Python programming. Feel free to contribute.

I will update every once in a while, so check back…

  • Fastest string conversion :
>>> a=123
>>> `a` 
'123'
  • Fastest string concatenation :
>>> ''.join['a','b','c'] 

Efficiency comparison

Optimization Anecdote (Guido van Rossum)

  • Generator Functions
>>> a=[1,2,3]
>>> b=[x**2 for x in a] 
b=[1,4,9]
  • Timing a process :
from time import clock
t=clock()
... 
t=clock()-t

  • 100% CPU Usage Simple Script :
while True : pass
  • Hash and MD5
>>> a='123'
>>> hash(a)
1911471187
>>> md5(a).digest ()
' ,\xb9b\xacY\x07[\x96K\x07\x15-#Kp'
  • Code Optimization
import psyco 
..
psyco.full()
  • Compact Code

If possible, try to define less functions, and keep their code in your main function. This of course, reduces code readability and reusability, but it can sometimes (and in extreme cases) give you a slight performance gain. In addition to that, try not to use to many “dots”.

e.g. : Instead of using :

>>>'123'.replace('1','2')

better use :

>>> rep=str.replace
>>> rep('123','1','2')
  • Urllib

There is a very easy way to open and post data to a URL.

>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
  • File handling

The easiest way to open a file.

>>> f=open('testfile.txt')
>>> f=open('testfile.txt','w') #Open a file to write.

Useful Links

Compiled Python

Sage

NetworkX

PIL

Pygame

Psyco

Win32 Extensions

Matplotlib

Numpy

SciPy

VideoCapture

Swig

ONLamp Scientific Python

MCI Interface

ReportLab

PyPdf

 

Leave a Reply