Numpy is taking more time in simple math than pure python3, I thought it was the opposite until I wrote some scripts with timeit to prove it.
With simple maths i mean sqrt, power, and small array transformations like showed in my script.
My versions:
- Python 3.4.3
- OS Ubuntu 14.04
- Numpy 1.10.0.post2
Here is my script:
import timeit
import random
import numpy as np
from math import sqrt
# Transformation
def x1y1x2y2_to_x1y1wh():
rectangle = np.random.rand(4)
return (rectangle[0], rectangle[1], rectangle[2] - rectangle[0],
rectangle[3] - rectangle[1])
transf_arr = [[1,0,-1,0], [0,1,0,-1], [0,0,1,0], [0,0,0,1]]
def x1y1x2y2_to_x1y1wh_np():
rectangle = np.random.rand(4)
return np.dot([rectangle], transf_arr)
t2 = timeit.timeit(x1y1x2y2_to_x1y1wh_np, number = 100000)
t1 = timeit.timeit(x1y1x2y2_to_x1y1wh, number = 100000)
print('Pyth rectangle transf.: %s' % t1)
print('NP rectangle transf.: %s' % t2)
# Power
def pow_pyth():
return pow(random.randint(0,1000), 2)
def pow_np():
return np.power(random.randint(0,1000), 2)
t1 = timeit.timeit(pow_pyth, number=10000)
t2 = timeit.timeit(pow_np, number=10000)
print('Pyth pow: %s' % t1)
print('NP pow: %s' % t2)
# SQRT
def sqrt_pyth():
return sqrt(random.randint(0,1000))
def sqrt_np():
return np.sqrt(random.randint(0,1000))
t1 = timeit.timeit(sqrt_pyth, number=10000)
t2 = timeit.timeit(sqrt_np, number=10000)
print('Pyth sqrt: %s' % t1)
print('NP sqrt: %s' % t2)
Outputs:
Pyth rectangle transf.: 0.15777392499876441
NP rectangle transf.: 0.664924152999447
Pyth pow: 0.01462321399958455
NP pow: 0.02568346400221344
Pyth sqrt: 0.011927954001293983
NP sqrt: 0.019845947001158493
Is it right or I'm doing something wrong?