Testing, profiling and optimization Flashcards
pytest of factorial(order)
import pytest
from script import factorial
def test_factorial(): assert factorial(3) == 6
if __name__ == “__main__”:
pytest.main(“thisfile.py”)
doctest of factorial(order)
def factorial(order): """ >>> factorial(3) 6 """
profile factorial(6)
import cProfile
import pstats
from script import factorial
cProfile.run(“factorial(6)”, “factorial”)
pstats.Stats(“factorial”).print_stats()
time factorial(6)
from timeit import timeit
timeit(“factorial(6)”, “from script import factorial”, number=100000)
time a block of code
from time import time
timer = time() # Do something timer = time() - timer print timer
optimization in python
Local name space > Global name space
if-elif-else > try-except-default
Few function arguments > Many function arguments
xrange > range
Python native initialisation > Numpy initialisation
Numpy iteration > Python native iteration
weave
from scipy import weave
weave.inline(“””//code”””, [‘var1’, ‘var2’], type_converters = weave.converters.blitz, headers = [’’])
NB! Primitive types are copied (I think)