Numpy矩阵创建时间奇怪

我的应用程序需要一个起始矩阵,其中每一列与前一列交错 1。它将包含代表一个信号的数百万个复数,但一个小例子是:

array([[ 0,  1,  2,  3],
       [ 1,  2,  3,  4],
       [ 2,  3,  4,  5],
       [ 3,  4,  5,  6],
       [ 4,  5,  6,  7],
       [ 5,  6,  7,  8],
       [ 6,  7,  8,  9],
       [ 7,  8,  9, 10]])

我尝试了两种创建方法,一种快,一种慢。我不明白为什么快速矩阵创建方法会导致后续计算运行缓慢,而慢速矩阵创建会导致计算运行速度更快。子程序 calcs() 仅使用 FFT 来提供最少的代码来演示我在实际信号处理代码中看到的问题。示例运行产生:

python ex.py 
Slow Create, Fast Math
   57.90 ms, create
   36.79 ms, calcs()
   94.69 ms, total
Fast Create, Slow Math
   15.13 ms, create
  355.38 ms, calcs()
  370.50 ms, total

代码如下。任何见解将不胜感激!

import numpy as np
import time

N = 65536
Np = 64

# Random signal for demo.
x = np.random.randint(-50,50,N+Np) + 1j*np.random.randint(-50,50,N+Np)

def calcs(sig):
    np.fft.fft(sig)

print('Slow Create, Fast Math')
t0 = time.time()
X = np.zeros((N, Np), dtype=complex)
for col in range(Np):
    X[:,col] = x[col:col+N]
t1 = time.time()
calcs(X)
t2 = time.time()
print('  %6.2f ms, create' % (1e3 * (t1 - t0)))
print('  %6.2f ms, calcs()' % (1e3 * (t2 - t1)))
print('  %6.2f ms, total' % (1e3 * (t2 - t0)))

print('Fast Create, Slow Math')
t0 = time.time()
X = np.array([x[i:i+N] for i in range(Np)]).transpose()
t1 = time.time()
calcs(X)
t2 = time.time()
print('  %6.2f ms, create' % (1e3 * (t1 - t0)))
print('  %6.2f ms, calcs()' % (1e3 * (t2 - t1)))
print('  %6.2f ms, total' % (1e3 * (t2 - t0)))

以上是Numpy矩阵创建时间奇怪的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>