Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何提高此代码的性能_Python_Python 3.x_List Comprehension - Fatal编程技术网

Python 如何提高此代码的性能

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,

我试图减少这段代码的时间使用。 我的代码是计算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, 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