Python 如何提高此代码的性能
我试图减少这段代码的时间使用。 我的代码是计算2500只股票的指数移动平均数(作为ema(数据,周期)函数)Python 如何提高此代码的性能,python,python-3.x,list-comprehension,Python,Python 3.x,List Comprehension,我试图减少这段代码的时间使用。 我的代码是计算2500只股票的指数移动平均数(作为ema(数据,周期)函数) input:: stock_data[name] = [x,x,x....] output:: ema[stockname][period] = [x,x,x....] 我的代码: stock_names = ['ABC',...] #2500 name ema_periods = [5, 10, 11, 12, 13, 14, 15, 16, 20, 25, 30, 35,
input:: stock_data[name] = [x,x,x....]
output:: ema[stockname][period] = [x,x,x....]
我的代码:
stock_names = ['ABC',...] #2500 name
ema_periods = [5, 10, 11, 12, 13, 14, 15, 16, 20, 25, 30, 35, 40, 45, 50, 75, 90, 100, 200] #19 periods
# get data
stock_data = dict()
for name in stock_names:
stock_data[name] = get_stock_data(name) #each name keep 2000 values
start = time.time()
ema_dict = dict((key, dict((period, ema(stock_data[key], period)) for period in ema_periods)) for key in stock_data.keys())
print('elasped : ', time.time()-start)
我已经运行了10次
平均弹性时间=17.60秒
我只想得到一些建议来提高我的绩效
ema_dict = dict((key, dict((period, ema(stock_data[key], period)) for period in ema_periods)) for key in stock_data.keys())
因为数据是模拟数据,所以它有更好的方法
谢谢。如评论所述,我们无法访问所有的例程,但在这里仍然可以加快速度
- 使用dict comprehension而不是generator comprehension发出元组以馈送到dict。创建
需要花费时间。这里有两个嵌套的潜在dict comp元组
- 每次不按键访问
字典。可以按键和值进行迭代stock\u数据
ema_dict = {key : {period: ema(value, period) for period in ema_periods} for key,value in stock_data.items()}
遵循同样的原理,第一个init循环可以这样写:
stock_data = {name:get_stock_data(name) for name in stock_names}
我认为性能瓶颈可能不在于此代码,而在于
get\u stock\u data(..)
或ema(..)
。什么是get\u stock\u data
和ema
?