2016-04-29 2 views
4

У меня есть этот код С целью оптимизацииОптимизировать 2 петли в C

#include <math.h> 

void baseline (int n, float a[n][n],float b[n], float c[n]) 
{ 
    int i, j; 

for (j=0; j<n; j++) 
     for (i=0; i<n; i++) 
     a[j][i] = expl (b[i] + c[j]); 
} 

Так что я пытался вывезти экспоненциальный, потому что: ехр (а + Ь) = ехр (а) * ехр (б)

for (j=0; j<n; j++) 
{ 
    ej=exp(c[j]); 
    for (i=0; i<n; i++) 
    a[i][j] = exp (b[i]) *ej; 
} 

у меня есть инструмент, который дал мне информацию о своей программе и предложения по оптимизации его лучше

Section 1.1: Source loop ending at line 9 
========================================= 

Composition and unrolling 
------------------------- 
It is composed of the loop 5 
and is not unrolled or unrolled with no peel/tail loop. 

Section 1.1.1: Binary loop #5 
============================= 

The loop is defined in /home/haddad/Documents/Sujet1/kernel.c:8-9 
In the binary file, the address of the loop is: 400a08 
Warnings: 
Detected a function call instruction: 
Ignoring called function instructions 


1% of peak computational performance is used (0.20 out of 16.00 FLOP per cycle (GFLOPS @ 1GHz)) 

Obsolete instructions 
--------------------- 
Detected X87 INSTRUCTIONS. 
x87 is the legacy x86 extension to process FP values. This instruction set is much less efficient than SSE or AVX. In particular, it does not support vectorization (x87 units not being vector units). 
A recent compiler should never generate x87 code as soon as you don't use any 80 bits FP elements or complex divides in your code. 

If you don't need 80 bits precision, use only single or double precision elements in your code and then, if necessary, tune your compiler to make it generate only SSE or AVX instructions. 
If complex divides are used, use fcx-limited-range that is included in ffast-math (see manual for safe usage). 


Code clean check 
---------------- 
Detected a slowdown caused by scalar integer instructions (typically used for address computation). 
By removing them, you can lower the cost of an iteration from 5.00 to 2.00 cycles (2.50x speedup). 

Vectorization status 
-------------------- 
Your loop is not vectorized (all SSE/AVX instructions are used in scalar mode). 
Only 12% of vector length is used. 


Vectorization 
------------- 
Your loop is processing FP elements but is NOT OR PARTIALLY VECTORIZED and could benefit from full vectorization. 
By fully vectorizing your loop, you can lower the cost of an iteration from 5.00 to 0.75 cycles (6.67x speedup). 
Since your execution units are vector units, only a fully vectorized loop can use their full power. 

Two propositions: 
- Try another compiler or update/tune your current one: 
- Remove inter-iterations dependences from your loop and make it unit-stride. 
    * If your arrays have 2 or more dimensions, check whether elements are accessed contiguously and, otherwise, try to permute loops accordingly: 
C storage order is row-major: for(i) for(j) a[j][i] = b[j][i]; (slow, non stride 1) => for(i) for(j) a[i][j] = b[i][j]; (fast, stride 1) 
    * If your loop streams arrays of structures (AoS), try to use structures of arrays instead (SoA): 
for(i) a[i].x = b[i].x; (slow, non stride 1) => for(i) a.x[i] = b.x[i]; (fast, stride 1) 


Bottlenecks 
----------- 
Front-end is a bottleneck. 
The store unit is a bottleneck. 

Try to reduce the number of stores. 
For example, provide more information to your compiler: 
- hardcode the bounds of the corresponding 'for' loop, 
- use the 'restrict' C99 keyword 


Complex instructions 
-------------------- 
Detected COMPLEX INSTRUCTIONS. 

These instructions generate more than one micro-operation and only one of them can be decoded during a cycle and the extra micro-operations increase pressure on execution units. 
CALL: 1 occurrences 
FSTP: 1 occurrences 

- Pass to your compiler a micro-architecture specialization option: 
    * use march=native. 


Type of elements and instruction set 
------------------------------------ 
1 SSE or AVX instructions are processing arithmetic or math operations on single precision FP elements in scalar mode (one at a time). 


Matching between your loop (in the source code) and the binary loop 
------------------------------------------------------------------- 
The binary loop is composed of 1 FP arithmetical operations: 
- 1: addition or subtraction 
The binary loop is loading 12 bytes (3 single precision FP elements). 
The binary loop is storing 18 bytes (4 single precision FP elements). 


Arithmetic intensity 
-------------------- 
Arithmetic intensity is 0.03 FP operations per loaded or stored byte. 


Unroll opportunity 
------------------ 
Loop is data access bound. 

Я хотел бы:

-Использования уникального для вместо 2, если это возможно

-Vectorise петель с использованием OpenMP

й изменить экспоненциальные другое выражение менее дорогой ..

Спасибо.

+0

Есть ли что-нибудь особенное в '' '' '' '' 'массивах? Постоянны ли они? Являются ли они целыми? Имеют ли они уникальные или сильно повторяющиеся ценности? Есть ли какие-то ограничения на их ценности? –

+0

они имеют тип float, содержат случайное значение между 0 и RAND_MAX – unfoudev

+0

'RAND_MAX' является целым числом –

ответ

6

вы расчет exp(b[i])n раз вместо когда-то:

float exp_b[n]; 
for (j=0; j<n; j++) 
{ 
    exp_b[j] = exp(b[j]); 
} 

for (j=0; j<n; j++) 
{ 
    ej=exp(c[j]); 
    for (i=0; i<n; i++) 
     a[i][j] = exp_b[i] *ej; 
} 

это решение только вызывает функцию exp2 * n раз, в то время как ваши называет это n * n раз, так что вы сохраните (n - 2) * nexp вызовов функций.

+1

@WeatherVane, но вместо примера OP это действительно уменьшает требуемый расчет. Функция 'exp' будет вызываться только n + n' раз, а не' n * n' раз. – mch

+0

Было бы легче увидеть преимущество, если первый цикл использовал 'i' для зеркалирования внутреннего цикла. –

+0

Да, я не видел его сначала по причине, указанной выше. –