I'm having trouble finding a solution to speed up a for loop in python. The following code does exactly what i want but is really slow :
# CoordEtAngle is an array containing 5 columns
# 1, 2 and 3 column are x y z coordinate of a points
# 4 and 5 values corresponding to those points
points=CoordEtAngle[:,0:3]
NumElem=np.zeros((len(allElem)), dtype=int)
CoordAxelist=[]
for idx,elemcur in enumerate(allElem):
Coord = np.asarray(map(lambda i: allNodes[i].coordinates, elemcur.connectivity)) # gives me an array containing x,y and z coordinate of a box for each elements
min_x=np.min(Coord[:,0])
max_x=np.max(Coord[:,0])
min_y=np.min(Coord[:,1])
max_y=np.max(Coord[:,1])
min_z=np.min(Coord[:,2])
max_z=np.max(Coord[:,2])
bound_x = np.logical_and(points[:, 0] > min_x, points[:, 0] < max_x)
bound_y = np.logical_and(points[:, 1] > min_y, points[:, 1] < max_y)
bound_z = np.logical_and(points[:, 2] > min_z, points[:, 2] < max_z)
bb_filter = np.logical_and(np.logical_and(bound_x, bound_y), bound_z)
NumElem[idx]=np.int(elemcur.label)
CoordAxelist.append([np.mean(CoordEtAngle[bb_filter,3]),np.mean(CoordEtAngle[bb_filter,4])])
CoordAxelist=np.concatenate(CoordAxelist)
Thanks in advance for your input. I have a technical issue and i can only use numpy library ...
I did manage to gain some speed using lambda and map in some part of the loop but have no idea how to get even better results
CodePudding user response:
Thanks to both of you. allElem is not a numpy array but i could have it in numpy array, could it help ?
CodePudding user response:
I have several suggestions for you to try:
- Try to pre allocate
CoordAxelist
before your loop starts - Try replacing enumerate with numpy.ndenumerate
- You can profile your code with cProfile. You can read how to use this profiling tool in this question