我試着優化下面的代碼,但我無法弄清楚如何提高計算速度。下面的代碼需要將近30秒才能運行。這是因爲bootsam和filedata矩陣需要時間。有人可以幫助我優化此代碼 是否有可能提高性能?Python:如何優化此代碼
import numpy as np
filedata=np.genfromtxt('monthlydata1970to2010.txt',dtype='str') # this will creae 980 * 7 matrix
nboot=5000
results=np.zeros((11,nboot)); #this will create 11*5000 matrix
results[0,:]=600
horizon=360
balance=200
bootsam=np.random.randint(984, size=(984, nboot)) # this will create 984*5000 matrix
for bs in range(0,nboot):
for mn in range(1,horizon+1):
if mn%12 ==1:
bondbal = 24*balance
sp500bal=34*balance
russbal = 44*balance
eafebal=55*balance
cashbal =66*balance
bondbal=bondbal*(1+float(filedata[bootsam[mn-1,bs]-1,2]))
sp500bal=sp500bal*(1+float(filedata[bootsam[mn-1,bs]-1,3]))
russbal=russbal*(1+float(filedata[bootsam[mn-1,bs]-1,4]))
eafebal=eafebal*(1+float(filedata[bootsam[mn-1,bs]-1,5]))
cashbal=cashbal*(1+float(filedata[bootsam[mn-1,bs]-1,6]))
balance=bondbal + sp500bal + russbal + eafebal + cashbal
else:
bondbal=bondbal*(1+float(filedata[bootsam[mn-1,bs]-1,2]))
sp500bal=sp500bal*(1+float(filedata[bootsam[mn-1,bs]-1,3]))
russbal=russbal*(1+float(filedata[bootsam[mn-1,bs]-1,4]))
eafebal=eafebal*(1+float(filedata[bootsam[mn-1,bs]-1,5]))
cashbal=cashbal*(1+float(filedata[bootsam[mn-1,bs]-1,6]))
balance=bondbal + sp500bal + russbal + eafebal + cashbal
if mn == 60:
results[1,bs]=balance
if mn == 120:
results[2,bs]=balance
if mn == 180:
results[3,bs]=balance
if mn == 240:
results[4,bs]=balance
if mn == 300:
results[5,bs]=balance
'1 + float(100)'與'101'是一回事。' – mgilson 2013-03-01 05:05:41
如果你說你正在用代碼做什麼而不是詢問如何改進它,這可能會有所幫助。 – 2013-03-01 05:07:06
使用'timeit'模塊,如果你想檢查它所花費的時間量爲 – avasal 2013-03-01 05:08:28