Learn to write faster code by experimenting with this library

#pip install pythonbenchmark

###How-To: A typical use case is: I have functionX, and optimized functionX. Now I want to know if my modified version is faster and how much.

from pythonbenchmark import compare, measure
import time

a,b,c,d,e = 10,10,10,10,10
something = [a,b,c,d,e]

def myFunction(something):
    time.sleep(0.4)

def myOptimizedFunction(something):
    time.sleep(0.2)

# comparing test
compare(myFunction, myOptimizedFunction, 10, input)
# without input
compare(myFunction, myOptimizedFunction, 100)

Output

alt tag

Measuring execution time with the @measure decorator

from pythonbenchmark import compare, measure
import time

a,b,c,d,e = 10,10,10,10,10
something = [a,b,c,d,e]

@measure
def myFunction(something):
    time.sleep(0.4)

@measure
def myOptimizedFunction(something):
    time.sleep(0.2)

myFunction(input)
myOptimizedFunction(input)

Output

alt tag


Do experiments, have fun!
Make incremental changes to your high performance code and see how much speed improvement you gain with each modification. This will give you an enormous intuition about how to write fast code :)

Analytics