11. Be careful with type mactching in mixed Python-Fortran software (e.g. flat/ real*8): if the array entry types do not match, arrays will be copied!
Avoid explicit loops: use vectorizd numpy expressions instead. If you really need a loop, then try list comprehensions as they are in general much faster. Example:
1 2 3 4 5 6 7 8 9 10 11 12 # Slow: x = [] for i in xrange(8): x.append( i**2 ) # Better: x = [0, 0, 0, 0, 0, 0, 0, 0] for i in xrange(len(x)): x[i] = i**2 # Best: x = [ i**2 for i in xrange(8) ] Avoid module prefix in frequently called funcions:Or even import the function into the global namespace:import mod func = mod.func for x in hugelist: func(x)
from mod import func for x in hugelist: func(x) Plain functions are called faster than class methods: trick:f = myobj.__call__ f(x) Inlining functions speeds-up the code Avoid usieng numpy functions with scalar arguments Use xrange instead of range (but be aware that xrange only supports a small part of the interface of range() and similar containers. [3]) if-else is faster than try-except (never use exceptions for program flow!) Avoid resizing of numpy arrays Callbacks to Python from Fortran/C/C++ are expensive Avoid unnecessary allocation of large data structures
12. Use asarray with parameter order=’Fortran’ when sending arrays from numpy to Fortran routines!
Optimization of Python Code
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment