【问题标题】:Tips on how to optimize the inner function with a large for loop关于如何使用大型 for 循环优化内部函数的提示
【发布时间】:2017-03-06 18:13:33
【问题描述】:
def testing(min_quadReq, stepsize, max_quadReq, S):
    y = np.arange(min_quadReq, max_quadReq, stepsize)
    print("Y", y)
    I_avg = np.zeros(len(y))
    Q_avg = np.zeros(len(y))
    x = np.arange(0, (len(S)))
    debugger = 0
    for i in range(0, len(y)):
        I = np.array(S * (np.cos(2 * np.pi * y[i] * x)))
        Q = np.array(S * (np.sin(2 * np.pi * y[i] * x)))
        I_avg[i] = np.sum(I, 0)
        Q_avg[i] = np.sum(Q, 0)
        debugger += 1
    D = [I_avg**2 + Q_avg**2]
    maxIndex = np.argmax(D)
    #maxValue = D.max()
    # in python is arctan2(b,a) compared to matlab's atan2(a,b)
    phaseOut = np.arctan2(Q_avg[maxIndex], I_avg[maxIndex])
    # returns the out value and the phase
    out = min_quadReq + ((maxIndex + 1) - 1) * stepsize
    return out, phaseOut

我正在开展一个项目,该项目使用 DSP 处理信号以获取相关数据。上面的代码来自正交调制的内部函数。据我所见,这是代码中最有可能被优化的部分。例如,两个 sum 函数分别被调用了大约 92k 次,而正交函数本身被调用了 2696 次。我对python不太熟悉,所以如果有人对如何更有效地编写它或一些好的文档有任何建议,那就太好了。

信号 S 是输入源,它是 [481][251] 的数组。正交的外壳由quadReq(cavSig[j, :]) 调用,只是一些额外的信息来显示它是如何调用的以及调用了多少次。

def randomnumber():
    s = np.random.random_sample((1, 251))
    print(s)
    return s

随机数()

编辑:添加了更多信息

【问题讨论】:

  • 请正确缩进您的代码。
  • 绝对可以优化。你需要阅读broadcastingthishere
  • 我投票结束这个问题,因为它属于代码审查网站。
  • 请将其移至 CodeReview.StackExchange.com。还包括一个完整的Minimal, complete, verifiable example——添加一个驱动程序,让其他人从头开始运行你的代码。
  • 关于y,你能告诉我们什么,尤其是步长?它不会将 S 的长度分开吗?还有长度?是不是比S小很多?

标签: python numpy optimization signal-processing


【解决方案1】:

您的循环为y 的每个元素生成一个I_avg 值。为了简洁起见,我可以将其写为列表理解。

In [61]: x=np.arange(4)
In [62]: y=np.arange(0,1,.2)
In [63]: [np.cos(2*np.pi*y[i]*x).sum() for i in range(y.shape[0])]
Out[63]: 
[4.0,
 -0.30901699437494745,
 0.80901699437494767,
 0.80901699437494834,
 -0.30901699437494756]

y[i]*x 部分只是yx 的外积,可以用np.outter 编写,也可以用广播y[:,None]*x 轻松编写。

In [64]: np.cos(2*np.pi*y[:,None]*x).sum(axis=1)
Out[64]: array([ 4.        , -0.30901699,  0.80901699,  0.80901699, -0.30901699])

进入交互式 Python 会话,并玩弄这样的表达式。最好的学习方式是做事并看到立竿见影的效果。保持测试表达式和数组的大小,以便您可以立即看到发生了什么。

【讨论】:

  • 谢谢,我会调查的
猜你喜欢
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2013-11-15
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
相关资源
最近更新 更多