加速码:在一定半径内寻找点数

2024-10-03 09:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我得找出海滩一定半径内搁浅的水母数量。我已经屏蔽了经纬度数组。 我的数组如下所示(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),它为每个timestep提供半径内果冻的数量。你知道吗

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)

Tags: andtheto代码falsetruelennp
1条回答
网友
1楼 · 发布于 2024-10-03 09:19:29

你要做的是对脚本进行“分析”。Python已经有了一个很好的分析工具cprofile:

https://docs.python.org/2/library/profile.html

甚至可以通过以下命令行调用cprofile:

python -m cprofile -o output_file python_script.py

从那里,您应该能够推断出代码中的瓶颈在哪里。你知道吗

相关问题 更多 >