Your Language
is FASTPython
is SLOWimport this
def calc(operation, a, b):
mapping = {
'add': lambda a, b: a + b,
'subtract': lambda a, b: a - b,
'multiply': lambda a, b: a * b,
'divide': lambda a, b: a / b,
}
return mapping[operation](a, b)
In [16]: %timeit calc('divide', 1, 2)
1000000 loops, best of 3: 699 ns per loop
In [17]: %prun calc('divide', 1, 2)
5 function calls in 0.000 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {built-in method exec}
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 <ipython-input-14-cf58e5c65b2c>:1(calc)
1 0.000 0.000 0.000 0.000 <ipython-input-14-cf58e5c65b2c>:6(<lambda>)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
def calc(operator, a, b):
if operator == 'add':
return a + b
elif operator == 'subtract':
return a - b
elif operator == 'multiply':
return a * b
elif operator == 'divide':
if b == 0:
raise ValueError('Unable divide to zero.')
return a / b
raise NotImplementedError
In [18]: %timeit calc('divide', 1, 2)
1000000 loops, best of 3: 258 ns per loop
In [19]: %prun calc('divide', 1, 2)
4 function calls in 0.000 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 {built-in method exec}
1 0.000 0.000 0.000 0.000 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 <ipython-input-17-966ad73e599d>:1(calc)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Python 2 optimizations
xrange
instead of range
'{0}'.format(...)
instead of
'{}'.format(...)
Django optimizations
.iterator()
for big collectionsforeign_id
instead of foreign__id
Slow Python
In [1]: import datetime
In [2]: %timeit datetime.datetime.strptime('2015-06-20', '%Y-%m-%d')
100000 loops, best of 3: 9.16 µs per loop
Fast Python
In [3]: from ciso8601 import parse_datetime
In [4]: %timeit parse_datetime('2015-06-20')
10000000 loops, best of 3: 144 ns per loop
Result: 63x Faster
Slow Python
In [9]: import json
In [10]: %timeit json.dumps({'key': 'value', 'date': datetime.date.today().isoformat()})
100000 loops, best of 3: 8.36 µs per loop
Fast Python
In [11]: import ujson
In [12]: %timeit ujson.dumps({'key': 'value', 'date': datetime.date.today().isoformat()})
100000 loops, best of 3: 4.6 µs per loop
Result: 2x faster
Slow Python. Python 2 only
In [2]: import pickle
In [3]: %timeit pickle.dumps({'key': 'value', 'date': datetime.date.today()})
10000 loops, best of 3: 36.1 µs per loop
Fast Python. Python 2 only
In [4]: import cPickle
In [5]: %timeit cPickle.dumps({'key': 'value', 'date': datetime.date.today()})
100000 loops, best of 3: 8.32 µs per loop
Result: 4.3x faster
Cython allows,
PyPy is a fast, compliant alternative implementation of the Python language
pypy yourfile.py
instead of
python yourfile.py