加速Python中的双循环

时间:2013-07-19 02:26:09

标签: python loops optimization numpy micro-optimization

有没有办法加快从上一次迭代更新其值的双循环?

在代码中:

def calc(N, m):
    x = 1.0
    y = 2.0
    container = np.zeros((N, 2))
    for i in range(N):
      for j in range(m):
        x=np.random.gamma(3,1.0/(y*y+4))
        y=np.random.normal(1.0/(x+1),1.0/sqrt(x+1))
      container[i, 0] = x
      container[i, 1] = y
    return container

calc(10, 5)

正如您所看到的,内部循环正在更新变量x和y,而外部循环每次都以不同的x值开始。我不认为这是可矢量化的,但可能还有其他可能的改进。

谢谢!

2 个答案:

答案 0 :(得分:1)

我认为它不会增加任何重要的加速,但是如果你一次生成所有的伽玛和正态分布的随机值,你可以保存一些函数调用。

Gamma函数有scaling property,因此如果从gamma(k,1)分布中绘制值x,则c*x将是从gamma中提取的值( k,c)分布。类似地,使用正态分布,您可以从正常(0,1)分布中获取y值,并将其转换为从执行x*s + m的正常(m,s)分布中提取的值。所以你可以按如下方式重写你的功能:

def calc(N, m):
    x = 1.0
    y = 2.0
    container = np.zeros((N, 2))
    nm = N*m
    gamma_vals = np.random.gamma(3, 1, size=(nm,))
    norm_vals = np.random.normal(0, 1, size=(nm,))
    for i in xrange(N):
        for j in xrange(m):
            ij = i*j
            x = gamma_vals[ij] / (y*y+4)
            y = norm_vals[ij]/np.sqrt(x+1) + 1/(x+1)
        container[i, 0] = x
        container[i, 1] = y
    return container

如果你的发行版的实际参数有一个更简单的表达式,你实际上可以使用一些精心设计的np.cumprod之类的形式,并为自己节省循环。我无法找到一种方法......

答案 1 :(得分:0)

这有用吗?

for i in xrange(N): 
   # xrange is an iterator, range makes a new list.
   # You save linear space and `malloc`ing time by doing this

    x += m*y # a simple algebra hack. Compute this line of the loop just once instead of `m` times
    y -= m*x
    y *= -1 # another simple algebra hack. Compute this line of the loop just once instead of `m` times
    container[i,0] = x
    container[i,1] = y
return container
相关问题