【问题标题】:Vectorize or optimize an loop where each iteration depends on the state of the previous iteration向量化或优化循环,其中每次迭代取决于前一次迭代的状态
【发布时间】:2017-11-07 20:39:20
【问题描述】:

我有一个在 python 中实现的算法。该算法可能会执行 1.000.000 次,所以我想尽可能地优化它。该算法的基数是三个列表(energypointvalList)和两个计数器pe

energypoint 这两个列表包含 0 到 1 之间的数字,我以此作为决策依据。 p 是积分计数器,e 是能量计数器。我可以用积分换取能量,每种能量的成本在valList 中定义(取决于时间)。我也可以用其他方式交易。但我必须一次全部交易。

算法概要:

  1. 获取一个布尔列表,其中energy 中的元素高于阈值,point 中的元素低于另一个阈值。这是一个用能量换积分的决定。获取相应的积分列表,用于决定用积分换取能量
  2. 在每个布尔列表中。删除在另一个真值之后出现的所有真值(如果我已将所有点换成能量,则不允许我再次这样做)
  3. 对于两个布尔列表中的每个项目对(pB,point bool 和eB,energy bool):如果 pB 为真并且我有积分,我想用我所有的积分换取能量。如果eB 是真的并且我有精力,我想用我所有的精力来换取积分。

这是我想出的实现:

start = time.time()
import numpy as np

np.random.seed(2) #Seed for deterministic result, just for debugging

topLimit = 0.55
bottomLimit = 0.45

#Generate three random arrays, will not be random in the real world
res = np.random.rand(500,3) #Will probably not be much longer than 500
energy = res[:,0]        
point = res[:,1]
valList = res[:,2]

#Step 1:
#Generate two bools that (for ex. energy) is true when energy is above a threashold
#and point below another threshold). The opposite applies to point
energyListBool = ((energy > topLimit) & (point < bottomLimit))
pointListBool = ((point > topLimit) & (energy < bottomLimit))

#Step 2:
#Remove all 'true' that comes after another true since this is not valid
energyListBool[1:] &= energyListBool[1:] ^ energyListBool[:-1]
pointListBool[1:] &= pointListBool[1:] ^ pointListBool[:-1]

p = 100
e = 0

#Step 3:
#Loop through the lists, if point is true, I loose all p but gain p/valList[i] for e
#If energy is true I loose all e but gain valList[i]*e for p
for i in range(len(energyListBool)):
    if pointListBool[i] and e == 0:
        e = p/valList[i] #Trade all points to energy
        p = 0
    elif energyListBool[i] and p == 0:
        p = valList[i]*e #Trade all enery to points
        e = 0

print('p = {0} (correct for seed 2: 3.1108006690739174)'.format(p))
print('e = {0} (correct for seed 2: 0)'.format(e))

end = time.time()
print(end - start)

我正在努力解决的是如何(如果可以的话)矢量化 for 循环,所以我可以使用它来代替我认为可能更快的 for 循环。

【问题讨论】:

    标签: python performance numpy optimization


    【解决方案1】:

    在当前的问题设置中这是不可能的,因为矢量化本质上要求您的 n-th 计算步骤不应依赖于先前的 n-1 步骤。然而,有时可以找到所谓的“封闭形式”的递归f(n) = F(f(n-1), f(n-2), ... f(n-k)),即找到不依赖于nf(n) 的显式表达式,但这是一个单独的研究问题。

    此外,从算法的角度来看,这样的矢量化不会带来很多好处,因为您的算法的复杂度仍然是 C*n = O(n)。但是,由于“复杂性常数”C 在实践中确实很重要,因此有不同的方法可以减少它。例如,用 C/C++ 重写关键循环应该不是什么大问题。

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2021-04-12
      • 2013-05-29
      • 1970-01-01
      • 2022-08-11
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多