我必须找到滞留在海滩某一半径范围内的水母数量。我已经屏蔽了纬度和经度数组。 我的数组看起来像这样(Xpos1和Ypos1相似):
Xpos1
masked_array(
data=[[50.04410171508789, 50.06398010253906, 50.08057403564453, ...,
--, --, --],
[49.99235534667969, 50.02357482910156, 50.0404052734375, ..., --,
--, --],
[50.04730987548828, 50.074710845947266, 50.092201232910156, ...,
--, --, --],
...,
[49.98905944824219, 50.507293701171875, 50.48957061767578, ...,
51.069766998291016, 50.74513626098633, 51.06978988647461],
[49.91417694091797, 50.510562896728516, 50.48354721069336, ...,
51.069766998291016, 50.95227813720703, 51.06978988647461],
[49.976619720458984, 50.504817962646484, 50.487918853759766, ...,
51.069766998291016, 50.75497817993164, 51.06978988647461]],
mask=[[False, False, False, ..., True, True, True],
[False, False, False, ..., True, True, True],
[False, False, False, ..., True, True, True],
...,
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False],
[False, False, False, ..., False, False, False]],
fill_value=9.96921e+36,
dtype=float32)
len(Xpos1[0])= 800 000 #Particle
len(Xpos1)=124 # Timesteps. Xpos1[0] is day 1 hour 1, Xpos1[1] is day 1 hour 2 and so on.
现在我必须找到哪些点靠近某个海滩。我目前的代码存在问题,如果我只采用Xpos [0:3],我需要5分钟来计算它,因为数组太大了。鉴于我需要检查几个区域,我目前的代码将花费我一生的时间来完成运行。
如何加速此代码?我想要的输出是一个数组(Blen),每个时间步长都会给出半径范围内的果冻量。
Blen=[124,253,100,...]
len(Blen)=124
我的代码是:
#Location of the beach I need to check
lonAa=2.631547
latAa=51.120983
#Frame
#1 degree longitude ||
LongDegree=2*pi*r*(np.cos(math.radians(LatM)))/360
#1 degree latitude =
LatDegree=2*pi*r/360
FrameRadius=10#km
Timestep=3 #Number of timesteps you want to check, for now only 3 and it already takes some time
#Make the frame within which the jellys have to be counted
FrameLeft=lonAAa-(FrameRadius/LongDegree)
FrameRight=lonAAa+(FrameRadius/LongDegree)
FrameUp=latAAa+(FrameRadius/LatDegree)
FrameDown=latAAa-(FrameRadius/LatDegree)
BFrame=np.zeros((Timestep,len(Xpos1[0])))
#And now the slow part
Blen=[]
for i in range (0,Timestep):
for j in range (0,len(Xpos1[0])):
if FrameDown<=Ypos1[i][j]<=FrameUp and FrameLeft<=Xpos1[i][j]<=FrameRight:
BFrame[i][j]=Ypos1[i][j]
Blen=np.count_nonzero(BFrame,axis=1)
答案 0 :(得分:0)
您要做的是称为“剖析”脚本。 Python已经有一个很好的分析工具叫做cprofile:
https://docs.python.org/2/library/profile.html
您甚至可以使用以下命令从命令行调用cprofile:
python -m cprofile -o output_file python_script.py
从那里,你应该能够推断代码中的瓶颈在哪里。