Numpy在简单数学上比纯python3花费更多时间

时间:2016-04-02 20:39:52

标签: python performance python-3.x numpy

Numpy在简单数学上花费的时间比纯python3要长,我认为这是相反的,直到我用时间来编写一些脚本来证明它。

使用简单的数学,我的意思是sqrt,power和小数组转换,如我的脚本中所示。

我的版本:

  • Python 3.4.3
  • OS Ubuntu 14.04
  • Numpy 1.10.0.post2

这是我的剧本:

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)

输出:

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

是对还是我做错了什么?

0 个答案:

没有答案