Tuesday 15 March 2011

performance - Are python lists row-major ordered or column-major ordered? -


I read on Wikipedia that the dragon is a language that implements line-command But I'm trying to multiply 2 metrics where I reach a line-up approach and using a column-head approach. But when I execute the code, the column-main approach is sharp all the way. I will post a piece of my code here:

  Class metrics: self.num_lines = num_lines Self: #flag indicates the type of matf def __init __ (self, num_lines, NUM_COLS, flag). NUM_COLS = NUM_COLS if flag == 0: # First Matrix self.matrix = [1] * num_lines * NUM_COLS elif flag == 1: # second matrix self.matrix = [0] * num_lines * NUM_COLS to the range I (num_lines ): range (num_cols) J: self.matrix [i * num_cols + j] = i + 1 elif flag == 2: # results matrix self.matrix = self.matrix = [0] * num_lines * num_cols def setMatrixValue ( self, line, column, value): self.matrix [line * self.num_cols + column] = value getMatrixValue (self, line, column) def return self.matrix [line * self.num_cols + column] def multiplyMatrices (num_lines , Num_cols, flag): matrix_a = matrix (num_lines, num_cols, 0) ma trix_b = matrix (num_cols, num_lines, 1) matrix_result = matrix (num_lines, num_lines, 2) # column-key approach that flag == 0: I range start_time = time.time () (Matriks_salt. Num_lines): G in the limit (Matriks_salt. Num_cols): temp = 0 k (matrix_a category. NUM_COLS): temp + = matrix_a.getMatrixValue (i, k) * matrix_b.getMatrixValue (k, j) matrix_result.setMatrixValue (i, j , Floating) # row-key approach elif flag == 1: start_time = time.time () I range (matrix_result.num_lines): for range in K (matrix_result.num_cols) for range: Range To switch to J. (matrix_a.num_lines): matrix_result.setMatrixValue (i, j, matrix_result.getMatrixValue (i, j) to + (matrix_a .getMatrixValue (i, k) * matrix_b.getMatrixValue (k, i))) End_time = time.time () print matrix_result.matrix diffTime (start_time, end_time)  

And I just realized that the matrix multiplication in Python was so slow n Java or C ++ Is there any reason?

The behavior you are expecting is due to the benefit of access to sequential memory. So here you want to increase the column in the internal loop.

  Automatics [line * self.num_cols + column]  

In pure Python there are some problems with this concept. Since all entries are objects- to reach them, you are already getting references (reference) in the list, but then you need to reach the memory of context (sequential) to get an object (bad). / P>

Fortunately there are alternatives, such as numpy. In addition, the Matrix routine that has been thoroughly tested, can be used by you.


No comments:

Post a Comment