Presentation is loading. Please wait.

Presentation is loading. Please wait.

ENERGY 211 / CME 211 Lecture 11 October 15, 2008.

Similar presentations


Presentation on theme: "ENERGY 211 / CME 211 Lecture 11 October 15, 2008."— Presentation transcript:

1 ENERGY 211 / CME 211 Lecture 11 October 15, 2008

2 Visualizing Pointers This assumes 32-bit addressing
0xffff00 0xffff04 0xffff08 4 0xffff00 6 int x = 4; int *p = &x; int y = *p + 2; This assumes 32-bit addressing p is of type “pointer to int”, not int! Modifying value of *p modifies x too

3 Matrix Allocation Strategies
There are two commonly-used methods for allocating memory for an m-by-n matrix Nested array: 1-D array of mn elements Multi-level array: 1-D, m-element array of 1-D n-element arrays

4 Nested Arrays Declaration and allocation:
double *A = new double[m*n]; To access (i,j) element: A[i*n+j] Advantages: contiguous memory efficient for iteration over whole matrix, efficient machine code for indexing Disadvantages: not intuitive, cumbersome to code element access

5 Visual: Nested Arrays Representation of a 3-by-4 matrix
(0,0) (0,1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3) (2,0) (2,1) (2,2) (2,3) Representation of a 3-by-4 matrix Declaration: double *A = new double[12]; Element indices zero-based To access (1,2) element, compute 1*4+2 and access A[6] Note row-major ordering

6 Multi-level Arrays Declaration and allocation:
double **A = new double *[m]; for (int i=0; i<m; i++) A[i] = new double[n]; To access (I,j) element: A[I][j] Advantages: intuitive structure, indexing Disadvantages: more multiplications per element access, rows not contiguous (how to address latter problem?)

7 Visual: Multi-level Arrays
double **A; A = new double *[3]; A[i] = new double[4]; Same matrix as in nested example A is an array of pointers! A[i] stores base address of array for row i

8 Improving Efficiency Consider a loop that accesses each element of an array in sequence To access x[i], machine code multiples i by size of element and adds to base address Instead, set pointer p equal to x Access element: *p, move to next: p++ Much more efficient: an increment instead of an addition and multiplication!

9 Loop Optimization Most of the running time is spent in loops, so focus optimizing efforts there The compiler can figure out many optimizations, but must be conservative Conditionals are very expensive, so handle special cases outside the loop Try to maintain locality: access data sequentially, to keep in cache But remember: “Premature optimization is the root of all evil” – Donald Knuth

10 Next Time Your questions! Pointers Project 2 Project 3 preview


Download ppt "ENERGY 211 / CME 211 Lecture 11 October 15, 2008."

Similar presentations


Ads by Google