wfl*_*nny 1 python numpy timeit
我编写了一个脚本来对我们的本地集群进行一些排名顺序相关计算。计算涉及寻找两个阵列,X和Y长度5000-10000的,并提取量
all((X[i], Y[i]))
all((X[i], not Y[i]))
all((not X[i], Y[i]))
Run Code Online (Sandbox Code Playgroud)
数千次计算(因为我洗牌X/Y除其他外)。
我们的一个集群运行的是 python2.4,所以我将alls更改为numpy.alls。然而,我估计需要大约 5-6 小时的计算达到了 24 小时以上。这让我进行了调查。
下面是一些示例代码:
In [2]: import timeit
In [3]: s = """import numpy as np
...: x, y = np.random.rand(1000), np.random.rand(1000)
...: [all((x[i], y[i])) for i in range(1000)]
...: """
In [4]: timeit.timeit(s, number=1000)
Out[4]: 0.39837288856506348
In [5]: s_numpy = """import numpy as np
...: x, y = np.random.rand(1000), np.random.rand(1000)
...: [np.all((x[i], y[i])) for i in range(1000)]
...: """
In [9]: timeit.timeit(s_numpy, number=1000)
Out[9]: 14.641073942184448
Run Code Online (Sandbox Code Playgroud)
任何线索为什么numpy.all需要 50 倍的时间来计算这个?是numpy.array开销吗?
编辑:我的原始数组numpy.array不像它们在这里 ( np.random.rand) 那样。我什至根本没有使用 numpy,直到我需要更改all行。但是,我已经用类似的东西替换了我的循环
np.sum(np.logical_and(X, Y))
np.sum(np.logical_and(X, np.logical_not(Y)))
np.sum(np.logical_and(np.logical_not(X), Y))
Run Code Online (Sandbox Code Playgroud)
这将初始开销的运行和大约 3000 个这些循环的计算速度加快了 60% 左右。谢谢!我将寻找更多使用 numpy 进行优化的方法。
[np.all((x[i], y[i])) for i in range(1000)]
Run Code Online (Sandbox Code Playgroud)
可以改写为
x = []
for i in range(1000):
x.append(numpy.all((x[i],y[i])))
Run Code Online (Sandbox Code Playgroud)
所以你在一个非常小的列表中调用 numpy.all
numpy 方法通常适用于更大的列表
timeit.timeit('all(x)','x = numpy.arange(1,100000)',number=1)
#~.0175
timeit.timeit('numpy.all(x)','x = numpy.arange(1,100000)',number=1)
#~.00043
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
797 次 |
| 最近记录: |