0

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?

Hamlett
  • 403
  • 6
  • 22
  • 1
    Refer : [Numpy slower than python?](http://stackoverflow.com/questions/16597066/why-is-numpy-slower-than-python-how-to-make-code-perform-better) – Ani Menon Apr 02 '16 at 20:45
  • @AniMenon So it's right, with small arrays it's better to use pure python. – Hamlett Apr 02 '16 at 20:52

0 Answers0