【发布时间】:2017-11-07 20:39:20
【问题描述】:
我有一个在 python 中实现的算法。该算法可能会执行 1.000.000 次,所以我想尽可能地优化它。该算法的基数是三个列表(energy、point 和valList)和两个计数器p 和e。
energy 和 point 这两个列表包含 0 到 1 之间的数字,我以此作为决策依据。 p 是积分计数器,e 是能量计数器。我可以用积分换取能量,每种能量的成本在valList 中定义(取决于时间)。我也可以用其他方式交易。但我必须一次全部交易。
算法概要:
- 获取一个布尔列表,其中
energy中的元素高于阈值,point中的元素低于另一个阈值。这是一个用能量换积分的决定。获取相应的积分列表,用于决定用积分换取能量 - 在每个布尔列表中。删除在另一个真值之后出现的所有真值(如果我已将所有点换成能量,则不允许我再次这样做)
- 对于两个布尔列表中的每个项目对(
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