Faster way to access 2D lists/arrays and do calculations in Python? -
i running 2 nested loops (first 1 120 runs, second 1 500 runs). in of 120x500 runs need access several lists , lists-in-lists (i call them 2d arrays).
at moment 120x500 runs take 4 seconds. of time taken 3 list appends , several 2d array accesses. arrays prefilled me outside of loops.
here code:
#range 0 119 cur_angle in range(0, __ar_angular_width-1): #range 0 499 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 , 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 figure out processing times via time.time() , building differences, didn't work reliable. calculated times fluctuating quite lot.
i not python pro, advices welcome. ideas how make code faster?
edit: initialization of arrays done code:
self.adjacent_dx = [i[:] in [[0]*(length_iterations-1)]*(angular_iterations-1)] self.opposite_dy = [i[:] in [[0]*(length_iterations-1)]*(angular_iterations-1)]
some general tips:
- try optimize algorithm best can.
- if it's possible, use pypy instead of regular python. doesn't require code modification if external dependencies work it.
- static typing , compilation c can add additional boost, requires simple code modifications. purpose can use cython.
note step 1 ofter hard , time consuming, giving small amounts of boost if have code, while steps 2 , 3 give dramatic boost without additional effort.
Comments
Post a Comment