【问题标题】:Speeding up code: finding the amount of points within a certain radius加速代码:查找一定半径内的点数
【发布时间】:2018-05-15 19:21:12
【问题描述】:

我必须找出搁浅在某个海滩半径内的水母数量。我已经屏蔽了纬度和经度数组。 我的数组看起来像这样(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)

【问题讨论】:

  • 定义一个边界框并首先检查其中的包含情况。

标签: python arrays performance numpy


【解决方案1】:

您要执行的操作称为“分析”脚本。 Python 已经有了一个很好的分析工具,叫做 cprofile:

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

您甚至可以从命令行调用 cprofile:

python -m cprofile -o output_file python_script.py

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 2016-07-21
    • 2017-08-05
    • 1970-01-01
    • 2013-09-12
    • 2022-07-25
    • 2020-09-23
    • 2017-04-13
    相关资源
    最近更新 更多