Performace tricks¶
use generators instead of lists were possible
run interpreter with
-O
For big ranges use
xrange()
cause it creates a generatorUse
xreadlines()
for big files cause it also creates a generatorSetting environment variable
PYTHONUNBUFFERED
will force stdout / stderr to be unbufferedos.fdopen("file", "r", 0)
to open file without bufferingUse
flush()
on filehandle to flush I/O bufferUse a list and
join
instead of string concatenationPrefer
while 1
instead of `` while True``Write “x < y < z” instead of “x < y and y < z”
"test " + var
is slower than"test %s" % (var,)
map()
, generator and list comprehension are faster than a loopput your global variables into a
main
function and call it by:
if __name__ == '__main__':
main()
profile your code
import profile
profile.run(“any_python_expression”)