(C ++) Passing through an array in four different ways using the same code

I do some calculations in a 2D array and have to go through the array in four different ways.

for(int i=0; i < array_size; i++) { for(int j=0; j < array_size; j++) { #do some computation around [i][j] element } } for(int i = array_size - 1; i >= 0; i--) { for(int j=0; j < array_size; j++) { #do the same computation around [i][j] element } } for(int i=0; i < array_size; i++) { for(int j=array_size - 1; j >= 0; j--) { #do the same computation around [i][j] element } } for(int i = array_size - 1; i >=0; i--) { for(int j = array_size - 1; j >= 0; j--) { #do the same computation around [i][j] element } } 

The fact is that, firstly, the calculation code is long and may also be changed in the future. Secondly, arrays are huge, so performance is also a problem.

I was wondering if there is a way to avoid code duplication and maintain performance. Since fetching code into a function is likely to slow performance.

+4
source share
1 answer

If you use the built-in function, your compiler will probably inlay for you, which will give you the result you want.

 inline void work(int i, int j) { ... } 

If you want to be more scientific about this, and this feature takes a non-trivial amount of time, I would recommend investing in a profiler. On the open source side, some people recommend gprof . On the property side, some people (including me) recommend Intel VTune .

+5
source

Source: https://habr.com/ru/post/1494990/


All Articles