I am running 2 nested loops (first one 120 runs, second one 500 runs). In most of the 120x500 runs I need to access several lists and lists-in-lists (I will call them 2D arrays).
At the moment the 120x500 runs take about 4 seconds. Most of the time is taken by the three list appends and several 2D array accesses. The arrays are prefilled by me outside of the loops.
Here is my code:
#Range from 0 to 119
for cur_angle in range(0, __ar_angular_width-1):
#Range from 0 to 499
for cur_length in range(0, int(__ar_length * range_res_scale)-1):
v_x = (auv_rot_mat_0_0*self.adjacent_dx[cur_angle][cur_length])+(auv_rot_mat_0_1*self.opposite_dy[cur_angle][cur_length])
v_y = (auv_rot_mat_1_0*self.adjacent_dx[cur_angle][cur_length])+(auv_rot_mat_1_1*self.opposite_dy[cur_angle][cur_length])
v_x_diff = (v_x+auv_trans_x) - ocp_grid_origin_x
v_y_diff = (v_y+auv_trans_y) - ocp_grid_origin_y
p_x = (m.floor(v_x_diff/ocp_grid_resolution))
p_y = (m.floor(v_y_diff/ocp_grid_resolution))
data_index = int(p_y * ocp_grid_width + p_x)
if data_index >= 0 and data_index < (len(ocp_grid.data)-1):
probability = ocp_grid.data[data_index]
if probability == 100:
if not m.isnan(self.v_directions[cur_angle]):
magnitude = m.pow(probability, 2) * self.magnitude_ab[cur_length]
ov_1 = self.v_directions[cur_angle]
ov_2 = magnitude
ov_3 = self.distances[cur_length]
obstacle_vectors.append(ov_1)
obstacle_vectors.append(ov_2)
obstacle_vectors.append(ov_3)
I tried to figure out the processing times via time.time() and building differences, but it didn't work reliable. The calculated times were fluctuating quite a lot.
I am not really a Python pro, so any advices are welcome. Any ideas how to make the code faster?
EDIT: The initialization of the arrays was done with this code:
self.adjacent_dx = [i[:] for i in [[0]*(length_iterations-1)]*(angular_iterations-1)]
self.opposite_dy = [i[:] for i in [[0]*(length_iterations-1)]*(angular_iterations-1)]
time.time()directly to time the results. Wrap your code in a specific function and use thetimeitmodule. In particular it's pretty simple to profile when using theIPythonconsole and its%timeitmagic.