相关疑难解决方法(0)

NumPy表现:uint8 vs.浮动和乘法与除法?

我刚刚注意到,通过仅将乘法变为除法,我的脚本的执行时间几乎减半.

为了研究这个,我写了一个小例子:

import numpy as np                                                                                                                                                                                
import timeit

# uint8 array
arr1 = np.random.randint(0, high=256, size=(100, 100), dtype=np.uint8)

# float32 array
arr2 = np.random.rand(100, 100).astype(np.float32)
arr2 *= 255.0


def arrmult(a):
    """ 
    mult, read-write iterator
    """
    b = a.copy()
    for item in np.nditer(b, op_flags=["readwrite"]):
        item[...] = (item + 5) * 0.5

def arrmult2(a):
    """ 
    mult, index iterator
    """
    b = a.copy()
    for i, j in np.ndindex(b.shape):
        b[i, j] = (b[i, j] + 5) * 0.5

def arrmult3(a):
    """
    mult, vectorized
    """ …
Run Code Online (Sandbox Code Playgroud)

python performance numpy python-2.7

16
推荐指数
2
解决办法
3286
查看次数

为什么numpy sum比+运算符慢10倍?

我注意到,非常紧张,np.sum比手写总和慢10倍.

带轴的np.sum:

p1 = np.random.rand(10000, 2)
def test(p1):
    return p1.sum(axis=1)
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)

每回路186μs±4.21μs(平均值±标准偏差,7次运行,每次1000次循环)

没有轴的np.sum:

p1 = np.random.rand(10000, 2)
def test(p1):
    return p1.sum()
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)

每回路17.9μs±236 ns(平均值±标准偏差,7次运行,每次10000次循环)

+:

p1 = np.random.rand(10000, 2)
def test(p1):
    return p1[:,0] + p1[:,1]
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)

每个环路15.8μs±328 ns(平均值±标准偏差,7次运行,每次100000次循环)

乘法:

p1 = np.random.rand(10000, 2)
def test(p1):
    return p1[:,0]*p1[:,1]
%timeit test(p1)
Run Code Online (Sandbox Code Playgroud)

每个环路15.7μs±701 ns(平均值±标准偏差,7次运行,每次10000次循环)

我没有看到任何理由.知道为什么吗?我的numpy版本是1.15.3.

编辑:10000000:

np.sum (with axis): 202 ms (5 x)
np.sum (without axis): 12 ms
+ : 46 ms (1 x)
* : 44.3 ms …
Run Code Online (Sandbox Code Playgroud)

python performance numpy

13
推荐指数
1
解决办法
753
查看次数

标签 统计

numpy ×2

performance ×2

python ×2

python-2.7 ×1