Python Forum
Try to Avoid for-loops for performance
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try to Avoid for-loops for performance
#2
If I run your code, after importing numpy as np and adding distances as empty list, it runs very fast.

I change the code a little bit.
import math
import numpy as np



def calc_dists(volume, list_of_points):
    hypot = math.hypot
    distances = np.zeros(volume.shape)
    for index, voxel in np.ndenumerate(vol):
        if voxel == 1:
            for index2 in list_of_points:
                distance = hypot(
                    index[0] - index2[0],
                    index[1] - index2[1],
                    index[2] - index2[2],
                )
                distances[index] = distance
    return distances

 
shape = (100,100,100)
vol = np.ones(shape)
points = [(2,3,2), (2,3,3) ,(2,6,4),(9,6,8)]
result = calc_dists(vol, points)

print(result)
A shape of 100 x 100 x 100 consists of 1e6 elements.
This code takes also under 10 seconds.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Try to Avoid for-loops for performance - by DeaD_EyE - Apr-01-2020, 10:06 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020