Faster Python

18
Faster Python Code in 5 minutes Anoop Thomas Mathew Profoundis Labs @atmb4u 31st August, 2013 PyCon India 2013

description

Faster Python Code in 5 minutes. Quick python optimization tips for beginners and advanced users.

Transcript of Faster Python

Page 1: Faster Python

Faster Python Code in 5 minutes

Anoop Thomas MathewProfoundis Labs

@atmb4u31st August, 2013PyCon India 2013

Page 2: Faster Python

➢@atmb4u➢ Co-Founder and CTO @ Profoundis Labs➢ Avid user of open source since 2003➢ Python and Django for last 4 years

AB

OU

T M

E

Page 3: Faster Python

Quick Profiling●%timeit and %prun in ipython●Try line_profiler● Not premature optimization

TIP

1

Page 4: Faster Python

use Iterators as possible

●Iterators and Generators are memory efficient and scalable●use itertools as much as possible

TIP

2

Page 5: Faster Python

list comprehension > for loop >

while loop

consider numpy and tuples for huge data

TIP

3

Page 6: Faster Python

xrange instead of rangeC version of range, designed to work with int

TIP

4

Page 7: Faster Python

map is a wonderful idea,

so is reduce and filtermap(function, data)

TIP

5

Page 8: Faster Python

Function calls are costly

●pass entire list to a function than iterating on each element and calling the function●Recursive loops are dangerous with quadratic complexity

TIP

6

Page 9: Faster Python

Local variables are faster

they are faster than global variables, builtins and attribute lookups

TIP

7

Page 10: Faster Python

delete the unnecessary

●use proper namespacing ●weakref is a good idea●use gc.collect() to expicitly collect the unused variables

TIP

8

Page 11: Faster Python

Threads for I/Octypes for CPU(GIL)

●use threads for I/O bound processes. ●For CPU bound with GIL lock, use gevent or C extensions to override it

TIP

9

Page 12: Faster Python

cProfilecStringIOcPickle ...

use C versions of library. They can be 100x faster.

TIP

10

Page 13: Faster Python

Standard Library &

builtin functions are always faster

TIP

11

Page 14: Faster Python

use try than if; given mostly True(exeptions exists: builtin functions are always faster)

NB: Bad practice!

TIP

12

Page 15: Faster Python

immutable types when possible

TIP

13

Page 16: Faster Python

●''.join('<string>') is faster than +●insert in a list is O(n)●Faster lookup in dict, set●deque for double sided operations

TIP

14

Page 17: Faster Python

Slides @http://www.slideshare.net/atmb4u/faster-python

More Infohttp://infiniteloop.in/blog/quick-python-performance-optimization-part-i/http://infiniteloop.in/blog/quick-python-performance-optimization-part-ii/http://wiki.python.org/moin/PythonSpeed/PerformanceTipshttp://wiki.python.org/moin/PythonSpeed

MO

RE

INFO

Page 18: Faster Python

TH

AN

K Y

OU

on twitter: @atmb4u