Python numpy数组的np.max(x,轴=1)和x.max(轴=1)之间的差异

Python numpy数组的np.max(x,轴=1)和x.max(轴=1)之间的差异,python,numpy,matrix,max,Python,Numpy,Matrix,Max,我试图得到numpy数组矩阵每一行的最大值。我想高效地实现它,为此我提出了以下两个习惯用法。我的问题是,以下两种方式之间是否存在性能差异 x = np.array([[1,2,3],[4,5,6],[7,8,9]]) #array([[1, 2, 3], # [4, 5, 6], # [7, 8, 9]]) np.max(x,axis = 1) #array([3, 6, 9]) x.max(axis = 1) #array([3, 6, 9]) 我在笔记本上进行了

我试图得到numpy数组矩阵每一行的最大值。我想高效地实现它,为此我提出了以下两个习惯用法。我的问题是,以下两种方式之间是否存在性能差异

x = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
#       [4, 5, 6],
#       [7, 8, 9]])

np.max(x,axis = 1)
#array([3, 6, 9])

x.max(axis = 1)
#array([3, 6, 9])

我在笔记本上进行了测试,您的第二种方法似乎稍微快一点:

import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
第一种方法:

%%timeit
np.max(x,axis = 1)

The slowest run took 11.75 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.71 µs per loop
第二种方法:

%%timeit
x.max(axis = 1)

The slowest run took 12.81 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.71 µs per loop
这大概是因为对于第一个,您将调用numpy模块,而对于第二个,它已经在对象中

但是,我建议不要尝试优化这些小事情,首先看看你是否已经做了其余的事情。你是否使用了像Numba这样的编译器,你是否使用了探查器来查看你的代码中有哪些部分正在减慢你的速度,等等