SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
Vetorização e
Otimização de Código
Luciano Palma
Community Manager – Servers & HPC
Intel Software do Brasil
Luciano.Palma@intel.com
Inovação acelerada em processadores
Multi Core Many Core
128 Bits
256 Bits
512 Bits
Intel inside, inside Intel…
Implementação Escalar
Modo Escalar
Uma instrução produz
um resultado
for (i=0;i<=MAX;i++)
c[i]=a[i]+b[i];
Implementação Vetorizada
Processamento SIMD
(vetorizado)
Instruções SSE, AVX, AVX2
Uma instrução pode produzir
múltiplos resultados
for (i=0;i<=MAX;i++)
c[i]=a[i]+b[i];
Vetores SIMD (AVX)
Como aproveitar isso tudo?
APIs nativas para multithreading demandam
experiência para escrever código correto e eficiente
– Mais complexo para expandir, especialmente para sistemas
que usam outros processos multithreaded.
Instruções de vetorização também apresentam desafios
– Inline assembly e intrinsics requerem experiência de baixo
nível e não escalam facilmente
– A vetorização feita pelo compilador é bem-vinda, mas pode
não funcionar sempre. Além disso, pode ser prejudicada pela
semântica da linguagem.
Construções de vetores com
Intel® Cilk™ Plus
Intel® Cilk™ Plus: solução simples e eficiente
Intel Cilk
Plus
Benefícios
Intel Cilk
Plus
O que é?
• Suportado pelo compilador:
3 simples palavras-chave
• Array notation
• Hyperobjects – evitam races de forma eficiente
• Pragmas e atributos para definir vetorização
• Suporta C and C++
• Sintaxe fácil de aprender e usar
• Código rápido e reutilizável (vetores maiores)
• Fork/join: simples de entender,
reproduz comportamento serial
• Baixo overhead: escalabilidade p/ muitos núcleos
• Reducers: + rápidos do que locks,
semântica do código serial
O que o Intel® Cilk™ Plus NÃO É
Não é uma solução completa para multithreading
Solução completa: Intel® Threading Building Blocks
Não é uma solução de paralelismo de cluster entre
diversos nós
Solucão: Intel® Cluster Studio
Não é uma ferramenta para tornar o projeto de aplicações
paralelas mais simples
Solução: Intel® Parallel Advisor
Técnicas de Vetorização
Notação de Arrays - Intel® Cilk™ Plus
Sintaxe para especificar seções dos arrays nas quais executar
determinadas operações
Sintaxe: [<limite inferior> : <tamanho> : <passo>]
• Exemplos
a[0:N] = b[0:N] * c[0:N];
a[:] = b[:] * c[:] // se a, b, c são declarados
com tamanho N
A vetorização automática do compilador C++ Intel® pode usar
essa informação para aplicar operações únicas para múltiplos
elementos do array usando Intel® Streaming SIMD Extensions
(Intel® SSE) e Intel® Advanced Vector Extensions (Intel® AVX)
• Exemplo mais avançado:
x[0:10:10] = sin(y[20:10:2]);
Exemplo de Notação de Arrays
void foo(double * a, double * b, double * c, double * d,
double * e, int n) {
for(int i = 0; i < n; i++)
a[i] *= (b[i] - d[i]) * (c[i] + e[i]);
}
void goo(double * a, double * b, double * c, double * d,
double * e, int n) {
a[0:n] *= (b[0:n] - d[0:n]) * (c[0:n] + e[0:n]);
}
icl -Qvec-report3 -c test-array-notations.cpp
Intel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build
20120410
Copyright (C) 1985-2012 Intel Corporation. All rights reserved.
test-array-notations.cpp
test-array-notations.cpp(2): (col. 2) remark: loop was not vectorized: existence of vector dependence.
test-array-notations.cpp(3): (col. 3) remark: vector dependence: assumed FLOW dependence between a
line 3 and e line 3.
<snip>
test-array-notations.cpp(7): (col. 6) remark: LOOP WAS VECTORIZED.
Vetorização + Threading
Quais loops podem ser vetorizados?
 Contável
Contador constante durante o loop
 Entradas e Saídas Únicas
Saída do loop não pode ser dependente de dados
(deve ser baseada no contador)
 Código “straight-line”
Instruções SIMD são iguais para diversas iterações do
loop. Não pode haver “branching”
 O mais interno de loops encadeados
 Sem chamadas de funções
Somente funções matemáticas intrínsecas ou inlines
http://d3f8ykwhia686p.cloudfront.net/1live/intel/CompilerAutovectorizationGuide.pdf
Funções vetorizadas pelo compilador
Funções Elementares no Intel® Cilk™ Plus
• O compilador não pode assumir que uma função definida
pelo usuário é segura para vetorização
• É possível tornar uma função “elementar”: indicar ao
compilador que a função pode ser aplicada a múltiplos
elementos de um array em paralelo de forma segura
• Utilize __declspec(vector) na declaração *E* na definição
da função, pois isso afetará o name-mangling
• Ao usar cláusulas disponíveis para ajudar diretamente o
compilador na geração do código, consulte a
documentação para detalhes
Exemplo de Função Elementar
double user_function(double x);
__declspec(vector) double elemental_function(double x);
double a[100];
double b[100];
void foo() {
a[:] = user_function(b[:]);
a[:] = elemental_function(b[:]);
}
icl /Qvec-report3 /c test-elemental-functions.cpp
Intel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build
20120410
Copyright (C) 1985-2012 Intel Corporation. All rights reserved.
test-elemental-functions.cpp
test-elemental-functions.cpp(9)
: (col. 4) remark: LOOP WAS VECTORIZED.
test-elemental-functions.cpp(8)
: (col. 4) remark: loop was not vectorized: nonstandard loop is not a vectorization candidate.
Obstáculos para Vetorização
Acesso não-contíguo à memória
"vectorization possible but seems inefficient“
Endereçamento indireto (3o exemplo):
“Existence of vector dependence”
Obstáculos para Vetorização
Dependência de Dados
No segundo caso, se não houver dependência
(aliasing), o uso de #pragma ivdep permite
“forçar” a vetorização
Intel® Cilk™ Plus - Tasking
Palavras-chave do Intel® Cilk™ Plus
Cilk Plus adiciona 3 palavras-chave ao C/C++:
_cilk_spawn
_cilk_sync
_cilk_for
Usando #include <cilk/cilk.h>, você pode usar as
palavras-chave: cilk_spawn, cilk_sync e cilk_for.
O runtime do CILK Plus controla a criação de threads e seu
agendamento. O pool de threads é criado antes do uso das
palavras-chave do CILK Plus.
Por default, o número de threads é igual ao número de
núcleos (incluindo hyperthreads), mas pode ser controlado
pelo usuário
cilk_spawn e cilk_sync
cilk_spawn dá ao runtime a
permissão para rodar uma função-filha de forma assíncrona.
– Não é criada (nem necessária) uma 2a thread!
– Se não houver workers disponíveis, a função-filha será
executada com uma chamada a uma função serial.
– O scheduler pode “roubar” a fila da função-pai e executá-la
em paralelo com a função-filha.
– A função-pai não tem garantia de rodar em paralelo com a
função-filha.
cilk_sync aguarda a conclusão de todas as funções-filhas
antes que a execução prossiga além daquele ponto.
– Existem pontos de sincronismo (cilk_sync) implícitos
Um exemplo simples
Computação recursiva do número de Fibonacci:
int fib(int n)
{
int x, y;
if (n < 2) return n;
x = cilk_spawn fib(n-1);
y = fib(n-2);
cilk_sync;
return x+y;
}
Chamadas assíncronas devem
completar antes de usar x.
Execução pode continuar
enquanto fib(n-1) roda.
cilk_for
Semelhante a um loop “for” regular.
cilk_for (int x = 0; x < 1000000; ++x) { … }
Qualquer iteração pode executar em paralelo com qualquer
outra.
Todas as interações completam antes do programa prosseguir.
Limitações:
– Limitado a uma única variável de controle.
– Deve ser capaz de voltar ao início de qualquer iteração,
randomicamente.
– Iterações devem ser independentes umas das outras.
Nos bastidores do cilk_for…
void run_loop(first, last) {
if ((last - first) < grainsize) {
for (int i=first; i<last ++i)
{LOOP_BODY;}
}
else {
int mid = (last-first)/2;
cilk_spawn run_loop(first, mid);
run_loop(mid, last);
}
}
Exemplos de cilk_for
cilk_for (int x; x < 1000000; x += 2) { … }
cilk_for (vector<int>::iterator x =
y.begin();
x != y.end(); ++x) { … }
cilk_for (list<int>::iterator x = y.begin();
x != y.end(); ++x) { … }
 O contador do loop não pode ser calculado em tempo de
compilação usando uma lista.
(y.end() – y.begin() não é definido)
 Não há acesso randômico aos elementos de uma lista.
(y.begin() + n não é definido.)
Serialização
Todo programa Cilk Plus tem um equivalente serial,
chamado de serialização
A serialização é obtida removendo as palavras-chave
cilk_spawn e cilk_sync e substituindo
cilk_for por for
O compilador produzirá a serialização se você
compilar com /Qcilk-serialize (Windows*) ou
–cilk-serialize (Linux*/OS X*)
Rodar um programa com somente um worker é
equivalente a rodar a serialização.
Semântica Serial
Um programa CILK Plus determinístico terá a mesma
semântica se sua serialização.
– Facilita a realização de testes de regressão;
– Facilita o debug:
– Roda com somente um núcleo
– Roda serializado
– Permite composição
– Vantagens dos hyperobjects
– Ferramentas de análise robustas (Cilk Plus SDK)
– cilkscreen race detector
– cilkview scalability analyzer
Sincronismos implícitos
void f() {
cilk_spawn g();
cilk_for (int x = 0; x < lots; ++x) {
...
}
try {
cilk_spawn h();
}
catch (...) {
...
}
} Ao final de uma funcão utilizando spawn
Ao final do corpo de um cilk_for (não sincroniza g())
Ao final de um bloco try contendo um spawn
Antes de entrar num bloco try contendo um sync
Composição
Sincronismos implícitos são importantes para tornar
cada chamada de função uma “caixa preta”.
Quem chama a função não sabe (nem se importa) se
a função chamada implementa spawns.
A abstração serial é mantida.
Que chama a função não precisa se preocupar com data
races na função chamada.
cilk_sync sincroniza somente funções-filhas que
foram “spawned” dentro da mesma função do sync:
nenhuma ação ocorre “à distância”.
Um exemplo de soma
int compute(const X& v);
int main()
{
const std::size_t n = 1000000;
extern X myArray[n];
// ...
int result = 0;
for (std::size_t i = 0; i < n; ++i)
{
result += compute(myArray[i]);
}
std::cout << "The result is: "
<< result
<< std::endl;
return 0;
}
Somando com Intel® Cilk™ Plus
int compute(const X& v);
int main()
{
const std::size_t n = 1000000;
extern X myArray[n];
// ...
int result = 0;
cilk_for (std::size_t i = 0; i < n; ++i)
{
result += compute(myArray[i]);
}
std::cout << "The result is: "
<< result
<< std::endl;
return 0;
}
Race!
Solução com Locks
int compute(const X& v);
int main()
{
const std::size_t n = 1000000;
extern X myArray[n];
// ...
mutex L;
int result = 0;
cilk_for (std::size_t i = 0; i < n; ++i)
{
int temp = compute(myArray[i]);
L.lock();
result += temp;
L.unlock();
}
std::cout << "The result is: "
<< result
<< std::endl;
return 0;
}
Problemas
Sobrecarga e
contenção dos
Locks
Solução com Reducer do CILK™ Plus
int compute(const X& v);
int main()
{
const std::size_t ARRAY_SIZE = 1000000;
extern X myArray[ARRAY_SIZE];
// ...
cilk::reducer_opadd<int> result;
cilk_for (std::size_t i = 0; i < ARRAY_SIZE; ++i)
{
result += compute(myArray[i]);
}
std::cout << "The result is: "
<< result.get_value()
<< std::endl;
return 0;
}
Declare result como
reducer de soma (int)
Atualizações são
resolvidas automatica/e,
sem races nem contenção
Ao final, o valor (int) pode
ser recuperado (soma)
Biblioteca de “HyperObjects”
A biblioteca de hyperobjects do Intel® Cilk™ Plus’s contém os
“reducers” mais utilizados (e mais) :
– reducer_list_append
– reducer_list_prepend
– reducer_max
– reducer_max_index
– reducer_min
– reducer_min_index
– reducer_opadd
– reducer_ostream
– reducer_basic_string
– holder
– …
Você pode escrever seu próprio reducer usando
cilk::monoid_base e cilk::reducer.
Use o Intel® Cilk™ Plus
Disponível em:
Intel® C++ Composer XE 2011
– Incluído no Intel® Parallel Studio XE 2011 SP1
– Avaliação gratuita (30 dias) em
http://software.intel.com/en-us/articles/intel-
software-evaluation-center/
Patch do gcc* 4.7 (Open Source)
– Obtenha em: http://cilk.com
Material complementar
Sobre Intel® Cilk™ Plus
http://cilk.com
Intel® Threading Building Blocks
http://threadingbuildingblocks.org
Suporte
http://premier.intel.com
Fóruns de usuários
http://software.intel.com/pt-br/forums
http://software.intel.com/en-us/forums/intel-cilk-plus
Apresentações técnicas
http://software.intel.com/en-us/articles/intel-software-
development-products-technical-presentations/
(incluem mais detalhes do Cilk Plus, vetorização, Intel® Cluster
Studio e muito mais!)
Nota sobre Otimização
• INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR
OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS
OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING
TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.
• A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or
death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL
AND ITS SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALL
CLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT
LIABILITY, PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITS
SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS.
• Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics
of any features or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever
for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design
with this information.
• The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published
specifications. Current characterized errata are available on request.
• Intel processor numbers are not a measure of performance. Processor numbers differentiate features within each processor family, not across different
processor families. Go to: http://www.intel.com/products/processor_number.
• Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.
• Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-
4725, or go to: http://www.intel.com/design/literature.htm
• Intel, Core, Atom, Pentium, Intel inside, Sponsors of Tomorrow, Pentium, 386, 486, DX2 and the Intel logo are trademarks of Intel Corporation in the
United States and other countries.
• *Other names and brands may be claimed as the property of others.
• Copyright ©2012 Intel Corporation.
Legal Disclaimer
Risk Factors
The above statements and any others in this document that refer to plans and expectations for the second quarter, the year and the future are forward-looking
statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,”
“will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions
also identify forward-looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors
could cause actual results to differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the
important factors that could cause actual results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due
to factors including changes in business and economic conditions, including supply constraints and other disruptions affecting customers; customer acceptance of
Intel’s and competitors’ products; changes in customer order patterns including order cancellations; and changes in the level of inventory at customers.
Uncertainty in global economic and financial conditions poses a risk that consumers and businesses may defer purchases in response to negative financial events,
which could negatively affect product demand and other related matters. Intel operates in intensely competitive industries that are characterized by a high
percentage of costs that are fixed or difficult to reduce in the short term and product demand that is highly variable and difficult to forecast. Revenue and the
gross margin percentage are affected by the timing of Intel product introductions and the demand for and market acceptance of Intel's products; actions taken
by Intel's competitors, including product offerings and introductions, marketing programs and pricing pressures and Intel’s response to such actions; and Intel’s
ability to respond quickly to technological developments and to incorporate new features into its products. Intel is in the process of transitioning to its next
generation of products on 22nm process technology, and there could be execution and timing issues associated with these changes, including products defects
and errata and lower than anticipated manufacturing yields. The gross margin percentage could vary significantly from expectations based on capacity utilization;
variations in inventory valuation, including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the
timing and execution of the manufacturing ramp and associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions
in the supply of materials or resources; product manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and
intangible assets. The majority of Intel’s non-marketable equity investment portfolio balance is concentrated in companies in the flash memory market segment,
and declines in this market segment or changes in management’s plans with respect to Intel’s investments in this market segment could result in significant
impairment charges, impacting restructuring charges as well as gains/losses on equity investments and interest and other. Intel's results could be affected by
adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict
and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain
marketing and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and
the level of revenue and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results could be affected by
adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving
intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports.
An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular
business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed
discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the report on Form 10-K for the year ended Dec.
31, 2011.
Rev. 4/17/12
Vetorização e otimização de código com Intel® CilkTM Plus

Contenu connexe

Tendances

Principais conceitos técnicas e modelos de programação paralela
Principais conceitos técnicas e modelos de programação paralelaPrincipais conceitos técnicas e modelos de programação paralela
Principais conceitos técnicas e modelos de programação paralelaIntel Software Brasil
 
Alocação Dinâmica em Linguagem C
Alocação Dinâmica em Linguagem CAlocação Dinâmica em Linguagem C
Alocação Dinâmica em Linguagem CGlécio Rodrigues
 
Aula 4 a linguagem assembly
Aula 4   a linguagem assemblyAula 4   a linguagem assembly
Aula 4 a linguagem assemblyLCCIMETRO
 
Hands On TensorFlow and Keras
Hands On TensorFlow and KerasHands On TensorFlow and Keras
Hands On TensorFlow and KerasSandro Moreira
 
Prova 2012 2_p4_gabarito
Prova 2012 2_p4_gabaritoProva 2012 2_p4_gabarito
Prova 2012 2_p4_gabaritoAmélia Moreira
 
C e assembly x86 64 v0.33.9
C e assembly x86 64 v0.33.9C e assembly x86 64 v0.33.9
C e assembly x86 64 v0.33.9Luciano Pereira
 
(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...
(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...
(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...Danilo J. S. Bellini
 
Arduino Day 2017 - Python + Arduino
Arduino Day 2017 - Python + ArduinoArduino Day 2017 - Python + Arduino
Arduino Day 2017 - Python + ArduinoEduardo S. Pereira
 
Aula 6 emu8086
Aula 6   emu8086Aula 6   emu8086
Aula 6 emu8086LCCIMETRO
 
Python: a primeira mordida
Python: a primeira mordidaPython: a primeira mordida
Python: a primeira mordidaBonoBee
 
Arduino sist u_controlados_intro_eletrica_2019_keynote_novo
Arduino sist u_controlados_intro_eletrica_2019_keynote_novoArduino sist u_controlados_intro_eletrica_2019_keynote_novo
Arduino sist u_controlados_intro_eletrica_2019_keynote_novoFernando Passold
 
Conjunto de instruções mips - instruções de desvio
Conjunto de instruções mips - instruções de desvioConjunto de instruções mips - instruções de desvio
Conjunto de instruções mips - instruções de desvioElaine Cecília Gatto
 
Introdução às Redes Neurais com PHP
Introdução às Redes Neurais com PHPIntrodução às Redes Neurais com PHP
Introdução às Redes Neurais com PHPOtávio Calaça Xavier
 

Tendances (20)

Principais conceitos técnicas e modelos de programação paralela
Principais conceitos técnicas e modelos de programação paralelaPrincipais conceitos técnicas e modelos de programação paralela
Principais conceitos técnicas e modelos de programação paralela
 
OpenMP
OpenMPOpenMP
OpenMP
 
Alocação Dinâmica em Linguagem C
Alocação Dinâmica em Linguagem CAlocação Dinâmica em Linguagem C
Alocação Dinâmica em Linguagem C
 
Aula 4 a linguagem assembly
Aula 4   a linguagem assemblyAula 4   a linguagem assembly
Aula 4 a linguagem assembly
 
Hands On TensorFlow and Keras
Hands On TensorFlow and KerasHands On TensorFlow and Keras
Hands On TensorFlow and Keras
 
Assembly
AssemblyAssembly
Assembly
 
Fit Metrocamp 2016
Fit Metrocamp 2016Fit Metrocamp 2016
Fit Metrocamp 2016
 
Prova 2012 2_p4_gabarito
Prova 2012 2_p4_gabaritoProva 2012 2_p4_gabarito
Prova 2012 2_p4_gabarito
 
C e assembly x86 64 v0.33.9
C e assembly x86 64 v0.33.9C e assembly x86 64 v0.33.9
C e assembly x86 64 v0.33.9
 
Biblioteca Allegro
Biblioteca AllegroBiblioteca Allegro
Biblioteca Allegro
 
(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...
(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...
(2013-05-20) [DevInSampa] AudioLazy - DSP expressivo e em tempo real para o P...
 
Ac16 conjunto de instruções v2
Ac16   conjunto de instruções v2Ac16   conjunto de instruções v2
Ac16 conjunto de instruções v2
 
Arduino Day 2017 - Python + Arduino
Arduino Day 2017 - Python + ArduinoArduino Day 2017 - Python + Arduino
Arduino Day 2017 - Python + Arduino
 
Aula 6 emu8086
Aula 6   emu8086Aula 6   emu8086
Aula 6 emu8086
 
Python: a primeira mordida
Python: a primeira mordidaPython: a primeira mordida
Python: a primeira mordida
 
Redes Neurais com PHP
Redes Neurais com PHPRedes Neurais com PHP
Redes Neurais com PHP
 
Arduino sist u_controlados_intro_eletrica_2019_keynote_novo
Arduino sist u_controlados_intro_eletrica_2019_keynote_novoArduino sist u_controlados_intro_eletrica_2019_keynote_novo
Arduino sist u_controlados_intro_eletrica_2019_keynote_novo
 
Conjunto de instruções mips - instruções de desvio
Conjunto de instruções mips - instruções de desvioConjunto de instruções mips - instruções de desvio
Conjunto de instruções mips - instruções de desvio
 
Introdução às Redes Neurais com PHP
Introdução às Redes Neurais com PHPIntrodução às Redes Neurais com PHP
Introdução às Redes Neurais com PHP
 
Tdc2010
Tdc2010Tdc2010
Tdc2010
 

En vedette

Identificando Hotspots e Intel® VTune™ Amplifier - Intel Software Conference
Identificando Hotspots e Intel® VTune™ Amplifier - Intel Software ConferenceIdentificando Hotspots e Intel® VTune™ Amplifier - Intel Software Conference
Identificando Hotspots e Intel® VTune™ Amplifier - Intel Software ConferenceIntel Software Brasil
 
Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013
Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013
Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013Intel Software Brasil
 
Intel® MPI Library e OpenMP* - Intel Software Conference 2013
Intel® MPI Library e OpenMP* - Intel Software Conference 2013Intel® MPI Library e OpenMP* - Intel Software Conference 2013
Intel® MPI Library e OpenMP* - Intel Software Conference 2013Intel Software Brasil
 
Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013
Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013
Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013Intel Software Brasil
 
Intel® VTune™ Amplifier - Intel Software Conference 2013
Intel® VTune™ Amplifier - Intel Software Conference 2013Intel® VTune™ Amplifier - Intel Software Conference 2013
Intel® VTune™ Amplifier - Intel Software Conference 2013Intel Software Brasil
 
Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013
Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013
Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013Intel Software Brasil
 
Escreva sua App sem gastar energia, agora no KitKat
Escreva sua App sem gastar energia, agora no KitKatEscreva sua App sem gastar energia, agora no KitKat
Escreva sua App sem gastar energia, agora no KitKatIntel Software Brasil
 
Desafios do Desenvolvimento Multi-plataforma
Desafios do Desenvolvimento Multi-plataformaDesafios do Desenvolvimento Multi-plataforma
Desafios do Desenvolvimento Multi-plataformaIntel Software Brasil
 
Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5
Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5
Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5Intel Software Brasil
 
Benchmarking para sistemas de alto desempenho
Benchmarking para sistemas de alto desempenhoBenchmarking para sistemas de alto desempenho
Benchmarking para sistemas de alto desempenhoIntel Software Brasil
 
Modernização de código em Xeon® e Xeon Phi™
Modernização de código em Xeon® e Xeon Phi™  Modernização de código em Xeon® e Xeon Phi™
Modernização de código em Xeon® e Xeon Phi™ Intel Software Brasil
 
Getting the maximum performance in distributed clusters Intel Cluster Studio XE
Getting the maximum performance in distributed clusters Intel Cluster Studio XEGetting the maximum performance in distributed clusters Intel Cluster Studio XE
Getting the maximum performance in distributed clusters Intel Cluster Studio XEIntel Software Brasil
 
Intel Technologies for High Performance Computing
Intel Technologies for High Performance ComputingIntel Technologies for High Performance Computing
Intel Technologies for High Performance ComputingIntel Software Brasil
 
Methods and practices to analyze the performance of your application with Int...
Methods and practices to analyze the performance of your application with Int...Methods and practices to analyze the performance of your application with Int...
Methods and practices to analyze the performance of your application with Int...Intel Software Brasil
 

En vedette (20)

Identificando Hotspots e Intel® VTune™ Amplifier - Intel Software Conference
Identificando Hotspots e Intel® VTune™ Amplifier - Intel Software ConferenceIdentificando Hotspots e Intel® VTune™ Amplifier - Intel Software Conference
Identificando Hotspots e Intel® VTune™ Amplifier - Intel Software Conference
 
Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013
Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013
Computação Paralela: Benefícios e Desafios - Intel Software Conference 2013
 
Intel® MPI Library e OpenMP* - Intel Software Conference 2013
Intel® MPI Library e OpenMP* - Intel Software Conference 2013Intel® MPI Library e OpenMP* - Intel Software Conference 2013
Intel® MPI Library e OpenMP* - Intel Software Conference 2013
 
Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013
Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013
Intel® Trace Analyzer e Collector (ITAC) - Intel Software Conference 2013
 
Intel® VTune™ Amplifier - Intel Software Conference 2013
Intel® VTune™ Amplifier - Intel Software Conference 2013Intel® VTune™ Amplifier - Intel Software Conference 2013
Intel® VTune™ Amplifier - Intel Software Conference 2013
 
Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013
Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013
Arquitetura do coprocessador Intel® Xeon Phi™ - Intel Software Conference 2013
 
Yocto - 7 masters
Yocto - 7 mastersYocto - 7 masters
Yocto - 7 masters
 
Intel tools to optimize HPC systems
Intel tools to optimize HPC systemsIntel tools to optimize HPC systems
Intel tools to optimize HPC systems
 
Escreva sua App sem gastar energia, agora no KitKat
Escreva sua App sem gastar energia, agora no KitKatEscreva sua App sem gastar energia, agora no KitKat
Escreva sua App sem gastar energia, agora no KitKat
 
Desafios do Desenvolvimento Multi-plataforma
Desafios do Desenvolvimento Multi-plataformaDesafios do Desenvolvimento Multi-plataforma
Desafios do Desenvolvimento Multi-plataforma
 
Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5
Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5
Desenvolvimento e análise de performance de jogos Android com Coco2d-HTML5
 
IoT FISL15
IoT FISL15IoT FISL15
IoT FISL15
 
Html5 fisl15
Html5 fisl15Html5 fisl15
Html5 fisl15
 
Benchmarking para sistemas de alto desempenho
Benchmarking para sistemas de alto desempenhoBenchmarking para sistemas de alto desempenho
Benchmarking para sistemas de alto desempenho
 
Modernização de código em Xeon® e Xeon Phi™
Modernização de código em Xeon® e Xeon Phi™  Modernização de código em Xeon® e Xeon Phi™
Modernização de código em Xeon® e Xeon Phi™
 
Getting the maximum performance in distributed clusters Intel Cluster Studio XE
Getting the maximum performance in distributed clusters Intel Cluster Studio XEGetting the maximum performance in distributed clusters Intel Cluster Studio XE
Getting the maximum performance in distributed clusters Intel Cluster Studio XE
 
Intel Technologies for High Performance Computing
Intel Technologies for High Performance ComputingIntel Technologies for High Performance Computing
Intel Technologies for High Performance Computing
 
Notes on NUMA architecture
Notes on NUMA architectureNotes on NUMA architecture
Notes on NUMA architecture
 
Methods and practices to analyze the performance of your application with Int...
Methods and practices to analyze the performance of your application with Int...Methods and practices to analyze the performance of your application with Int...
Methods and practices to analyze the performance of your application with Int...
 
CV-LucianoPalma
CV-LucianoPalmaCV-LucianoPalma
CV-LucianoPalma
 

Similaire à Vetorização e otimização de código com Intel® CilkTM Plus

FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!
FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!
FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!Intel Software Brasil
 
Codificação segura em C para sistemas embarcados
Codificação segura em C para sistemas embarcadosCodificação segura em C para sistemas embarcados
Codificação segura em C para sistemas embarcadoshenriqueprossi
 
Mini-curso Programação Paralela e Distribuída
Mini-curso Programação Paralela e DistribuídaMini-curso Programação Paralela e Distribuída
Mini-curso Programação Paralela e DistribuídaDeivid Martins
 
TDC2016SP - Trilha Node.Js
TDC2016SP - Trilha Node.JsTDC2016SP - Trilha Node.Js
TDC2016SP - Trilha Node.Jstdc-globalcode
 
TDC 2012 - Integração .NET x C++
TDC 2012 - Integração .NET x C++TDC 2012 - Integração .NET x C++
TDC 2012 - Integração .NET x C++Gabriel Guilherme
 
Criando sua própria linguagem de programação
Criando sua própria linguagem de programaçãoCriando sua própria linguagem de programação
Criando sua própria linguagem de programaçãoronaldoferraz
 
Simpósio Unicruz: OpenCV + Python (parte 1)
Simpósio Unicruz: OpenCV + Python (parte 1)Simpósio Unicruz: OpenCV + Python (parte 1)
Simpósio Unicruz: OpenCV + Python (parte 1)Cristiano Rafael Steffens
 
Visual Studio 2010 e C# 4
Visual Studio 2010 e C# 4Visual Studio 2010 e C# 4
Visual Studio 2010 e C# 4CDS
 
Relatório multiplexadores e decodificadores
Relatório multiplexadores e decodificadoresRelatório multiplexadores e decodificadores
Relatório multiplexadores e decodificadoresFlavio Oliveira Rodrigues
 
Desenvolvimento de Jogos com Cocos2d - Apresentação Coderockr Jam
Desenvolvimento de Jogos com Cocos2d - Apresentação Coderockr JamDesenvolvimento de Jogos com Cocos2d - Apresentação Coderockr Jam
Desenvolvimento de Jogos com Cocos2d - Apresentação Coderockr JamAndré Espeiorin
 
Integração continua sem traumas
Integração continua sem traumasIntegração continua sem traumas
Integração continua sem traumassabrinajn
 
Webinar: Uma introdução a ISA RISC-V e seu ecossistema
Webinar: Uma introdução a ISA RISC-V e seu ecossistemaWebinar: Uma introdução a ISA RISC-V e seu ecossistema
Webinar: Uma introdução a ISA RISC-V e seu ecossistemaEmbarcados
 
O que mudou no Ruby 1.9
O que mudou no Ruby 1.9O que mudou no Ruby 1.9
O que mudou no Ruby 1.9Nando Vieira
 
Programação Orientada a Testes
Programação Orientada a TestesProgramação Orientada a Testes
Programação Orientada a TestesGregorio Melo
 
Curso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como Código
Curso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como CódigoCurso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como Código
Curso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como CódigoGuilhermeJorgeAragod
 

Similaire à Vetorização e otimização de código com Intel® CilkTM Plus (20)

FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!
FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!
FISL14: Como domar uma fera de 1 TFlop que cabe na palma da sua mão!
 
Codificação segura em C para sistemas embarcados
Codificação segura em C para sistemas embarcadosCodificação segura em C para sistemas embarcados
Codificação segura em C para sistemas embarcados
 
Mini-curso Programação Paralela e Distribuída
Mini-curso Programação Paralela e DistribuídaMini-curso Programação Paralela e Distribuída
Mini-curso Programação Paralela e Distribuída
 
TDC2016SP - Trilha Node.Js
TDC2016SP - Trilha Node.JsTDC2016SP - Trilha Node.Js
TDC2016SP - Trilha Node.Js
 
Desenvolvimento iOS
Desenvolvimento iOSDesenvolvimento iOS
Desenvolvimento iOS
 
Curso de Node JS Básico
Curso de Node JS BásicoCurso de Node JS Básico
Curso de Node JS Básico
 
TDC 2012 - Integração .NET x C++
TDC 2012 - Integração .NET x C++TDC 2012 - Integração .NET x C++
TDC 2012 - Integração .NET x C++
 
Curso de java 02
Curso de java 02Curso de java 02
Curso de java 02
 
Criando sua própria linguagem de programação
Criando sua própria linguagem de programaçãoCriando sua própria linguagem de programação
Criando sua própria linguagem de programação
 
Simpósio Unicruz: OpenCV + Python (parte 1)
Simpósio Unicruz: OpenCV + Python (parte 1)Simpósio Unicruz: OpenCV + Python (parte 1)
Simpósio Unicruz: OpenCV + Python (parte 1)
 
Visual Studio 2010 e C# 4
Visual Studio 2010 e C# 4Visual Studio 2010 e C# 4
Visual Studio 2010 e C# 4
 
Introdução ao C#
Introdução ao C#Introdução ao C#
Introdução ao C#
 
Prova qco-2008.informática
Prova qco-2008.informáticaProva qco-2008.informática
Prova qco-2008.informática
 
Relatório multiplexadores e decodificadores
Relatório multiplexadores e decodificadoresRelatório multiplexadores e decodificadores
Relatório multiplexadores e decodificadores
 
Desenvolvimento de Jogos com Cocos2d - Apresentação Coderockr Jam
Desenvolvimento de Jogos com Cocos2d - Apresentação Coderockr JamDesenvolvimento de Jogos com Cocos2d - Apresentação Coderockr Jam
Desenvolvimento de Jogos com Cocos2d - Apresentação Coderockr Jam
 
Integração continua sem traumas
Integração continua sem traumasIntegração continua sem traumas
Integração continua sem traumas
 
Webinar: Uma introdução a ISA RISC-V e seu ecossistema
Webinar: Uma introdução a ISA RISC-V e seu ecossistemaWebinar: Uma introdução a ISA RISC-V e seu ecossistema
Webinar: Uma introdução a ISA RISC-V e seu ecossistema
 
O que mudou no Ruby 1.9
O que mudou no Ruby 1.9O que mudou no Ruby 1.9
O que mudou no Ruby 1.9
 
Programação Orientada a Testes
Programação Orientada a TestesProgramação Orientada a Testes
Programação Orientada a Testes
 
Curso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como Código
Curso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como CódigoCurso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como Código
Curso de Verão - Aula 03 - Introdução ao CI-CD e Infraestrutura como Código
 

Plus de Intel Software Brasil

Desafios do Desenvolvimento Multiplataforma
Desafios do Desenvolvimento MultiplataformaDesafios do Desenvolvimento Multiplataforma
Desafios do Desenvolvimento MultiplataformaIntel Software Brasil
 
Yocto no 1 IoT Day da Telefonica/Vivo
Yocto no 1 IoT Day da Telefonica/VivoYocto no 1 IoT Day da Telefonica/Vivo
Yocto no 1 IoT Day da Telefonica/VivoIntel Software Brasil
 
Otávio Salvador - Yocto project reduzindo -time to market- do seu próximo pr...
Otávio Salvador - Yocto project  reduzindo -time to market- do seu próximo pr...Otávio Salvador - Yocto project  reduzindo -time to market- do seu próximo pr...
Otávio Salvador - Yocto project reduzindo -time to market- do seu próximo pr...Intel Software Brasil
 
O uso de tecnologias Intel na implantação de sistemas de alto desempenho
O uso de tecnologias Intel na implantação de sistemas de alto desempenhoO uso de tecnologias Intel na implantação de sistemas de alto desempenho
O uso de tecnologias Intel na implantação de sistemas de alto desempenhoIntel Software Brasil
 
Escreva sua App Android sem gastar energia - Intel Sw Day
Escreva sua App Android sem gastar energia - Intel Sw DayEscreva sua App Android sem gastar energia - Intel Sw Day
Escreva sua App Android sem gastar energia - Intel Sw DayIntel Software Brasil
 
Using multitouch and sensors in Java
Using multitouch and sensors in JavaUsing multitouch and sensors in Java
Using multitouch and sensors in JavaIntel Software Brasil
 
Entenda de onde vem toda a potência do Intel® Xeon Phi™
Entenda de onde vem toda a potência do Intel® Xeon Phi™ Entenda de onde vem toda a potência do Intel® Xeon Phi™
Entenda de onde vem toda a potência do Intel® Xeon Phi™ Intel Software Brasil
 
Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...
Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...
Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...Intel Software Brasil
 
Livros eletrônicos interativos com html5 e e pub3
Livros eletrônicos interativos com html5 e e pub3Livros eletrônicos interativos com html5 e e pub3
Livros eletrônicos interativos com html5 e e pub3Intel Software Brasil
 
Intel XDK New - Intel Software Day 2013
Intel XDK New - Intel Software Day 2013Intel XDK New - Intel Software Day 2013
Intel XDK New - Intel Software Day 2013Intel Software Brasil
 

Plus de Intel Software Brasil (15)

Desafios do Desenvolvimento Multiplataforma
Desafios do Desenvolvimento MultiplataformaDesafios do Desenvolvimento Multiplataforma
Desafios do Desenvolvimento Multiplataforma
 
Yocto no 1 IoT Day da Telefonica/Vivo
Yocto no 1 IoT Day da Telefonica/VivoYocto no 1 IoT Day da Telefonica/Vivo
Yocto no 1 IoT Day da Telefonica/Vivo
 
IoT TDC Floripa 2014
IoT TDC Floripa 2014IoT TDC Floripa 2014
IoT TDC Floripa 2014
 
Otávio Salvador - Yocto project reduzindo -time to market- do seu próximo pr...
Otávio Salvador - Yocto project  reduzindo -time to market- do seu próximo pr...Otávio Salvador - Yocto project  reduzindo -time to market- do seu próximo pr...
Otávio Salvador - Yocto project reduzindo -time to market- do seu próximo pr...
 
Html5 tdc floripa_2014
Html5 tdc floripa_2014Html5 tdc floripa_2014
Html5 tdc floripa_2014
 
O uso de tecnologias Intel na implantação de sistemas de alto desempenho
O uso de tecnologias Intel na implantação de sistemas de alto desempenhoO uso de tecnologias Intel na implantação de sistemas de alto desempenho
O uso de tecnologias Intel na implantação de sistemas de alto desempenho
 
Escreva sua App Android sem gastar energia - Intel Sw Day
Escreva sua App Android sem gastar energia - Intel Sw DayEscreva sua App Android sem gastar energia - Intel Sw Day
Escreva sua App Android sem gastar energia - Intel Sw Day
 
Using multitouch and sensors in Java
Using multitouch and sensors in JavaUsing multitouch and sensors in Java
Using multitouch and sensors in Java
 
Entenda de onde vem toda a potência do Intel® Xeon Phi™
Entenda de onde vem toda a potência do Intel® Xeon Phi™ Entenda de onde vem toda a potência do Intel® Xeon Phi™
Entenda de onde vem toda a potência do Intel® Xeon Phi™
 
Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...
Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...
Across the Silicon Spectrum: Xeon Phi to Quark – Unleash the Performance in Y...
 
Livros eletrônicos interativos com html5 e e pub3
Livros eletrônicos interativos com html5 e e pub3Livros eletrônicos interativos com html5 e e pub3
Livros eletrônicos interativos com html5 e e pub3
 
Intel XDK New - Intel Software Day 2013
Intel XDK New - Intel Software Day 2013Intel XDK New - Intel Software Day 2013
Intel XDK New - Intel Software Day 2013
 
Hackeando a Sala de Aula
Hackeando a Sala de AulaHackeando a Sala de Aula
Hackeando a Sala de Aula
 
Android Native Apps Hands On
Android Native Apps Hands OnAndroid Native Apps Hands On
Android Native Apps Hands On
 
Android Fat Binaries
Android Fat BinariesAndroid Fat Binaries
Android Fat Binaries
 

Vetorização e otimização de código com Intel® CilkTM Plus

  • 1. Vetorização e Otimização de Código Luciano Palma Community Manager – Servers & HPC Intel Software do Brasil Luciano.Palma@intel.com
  • 2. Inovação acelerada em processadores Multi Core Many Core 128 Bits 256 Bits 512 Bits
  • 4. Implementação Escalar Modo Escalar Uma instrução produz um resultado for (i=0;i<=MAX;i++) c[i]=a[i]+b[i];
  • 5. Implementação Vetorizada Processamento SIMD (vetorizado) Instruções SSE, AVX, AVX2 Uma instrução pode produzir múltiplos resultados for (i=0;i<=MAX;i++) c[i]=a[i]+b[i];
  • 7. Como aproveitar isso tudo? APIs nativas para multithreading demandam experiência para escrever código correto e eficiente – Mais complexo para expandir, especialmente para sistemas que usam outros processos multithreaded. Instruções de vetorização também apresentam desafios – Inline assembly e intrinsics requerem experiência de baixo nível e não escalam facilmente – A vetorização feita pelo compilador é bem-vinda, mas pode não funcionar sempre. Além disso, pode ser prejudicada pela semântica da linguagem.
  • 8. Construções de vetores com Intel® Cilk™ Plus
  • 9. Intel® Cilk™ Plus: solução simples e eficiente Intel Cilk Plus Benefícios Intel Cilk Plus O que é? • Suportado pelo compilador: 3 simples palavras-chave • Array notation • Hyperobjects – evitam races de forma eficiente • Pragmas e atributos para definir vetorização • Suporta C and C++ • Sintaxe fácil de aprender e usar • Código rápido e reutilizável (vetores maiores) • Fork/join: simples de entender, reproduz comportamento serial • Baixo overhead: escalabilidade p/ muitos núcleos • Reducers: + rápidos do que locks, semântica do código serial
  • 10. O que o Intel® Cilk™ Plus NÃO É Não é uma solução completa para multithreading Solução completa: Intel® Threading Building Blocks Não é uma solução de paralelismo de cluster entre diversos nós Solucão: Intel® Cluster Studio Não é uma ferramenta para tornar o projeto de aplicações paralelas mais simples Solução: Intel® Parallel Advisor
  • 12. Notação de Arrays - Intel® Cilk™ Plus Sintaxe para especificar seções dos arrays nas quais executar determinadas operações Sintaxe: [<limite inferior> : <tamanho> : <passo>] • Exemplos a[0:N] = b[0:N] * c[0:N]; a[:] = b[:] * c[:] // se a, b, c são declarados com tamanho N A vetorização automática do compilador C++ Intel® pode usar essa informação para aplicar operações únicas para múltiplos elementos do array usando Intel® Streaming SIMD Extensions (Intel® SSE) e Intel® Advanced Vector Extensions (Intel® AVX) • Exemplo mais avançado: x[0:10:10] = sin(y[20:10:2]);
  • 13. Exemplo de Notação de Arrays void foo(double * a, double * b, double * c, double * d, double * e, int n) { for(int i = 0; i < n; i++) a[i] *= (b[i] - d[i]) * (c[i] + e[i]); } void goo(double * a, double * b, double * c, double * d, double * e, int n) { a[0:n] *= (b[0:n] - d[0:n]) * (c[0:n] + e[0:n]); } icl -Qvec-report3 -c test-array-notations.cpp Intel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build 20120410 Copyright (C) 1985-2012 Intel Corporation. All rights reserved. test-array-notations.cpp test-array-notations.cpp(2): (col. 2) remark: loop was not vectorized: existence of vector dependence. test-array-notations.cpp(3): (col. 3) remark: vector dependence: assumed FLOW dependence between a line 3 and e line 3. <snip> test-array-notations.cpp(7): (col. 6) remark: LOOP WAS VECTORIZED.
  • 15. Quais loops podem ser vetorizados?  Contável Contador constante durante o loop  Entradas e Saídas Únicas Saída do loop não pode ser dependente de dados (deve ser baseada no contador)  Código “straight-line” Instruções SIMD são iguais para diversas iterações do loop. Não pode haver “branching”  O mais interno de loops encadeados  Sem chamadas de funções Somente funções matemáticas intrínsecas ou inlines http://d3f8ykwhia686p.cloudfront.net/1live/intel/CompilerAutovectorizationGuide.pdf
  • 17. Funções Elementares no Intel® Cilk™ Plus • O compilador não pode assumir que uma função definida pelo usuário é segura para vetorização • É possível tornar uma função “elementar”: indicar ao compilador que a função pode ser aplicada a múltiplos elementos de um array em paralelo de forma segura • Utilize __declspec(vector) na declaração *E* na definição da função, pois isso afetará o name-mangling • Ao usar cláusulas disponíveis para ajudar diretamente o compilador na geração do código, consulte a documentação para detalhes
  • 18. Exemplo de Função Elementar double user_function(double x); __declspec(vector) double elemental_function(double x); double a[100]; double b[100]; void foo() { a[:] = user_function(b[:]); a[:] = elemental_function(b[:]); } icl /Qvec-report3 /c test-elemental-functions.cpp Intel(R) C++ Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 12.1.4.325 Build 20120410 Copyright (C) 1985-2012 Intel Corporation. All rights reserved. test-elemental-functions.cpp test-elemental-functions.cpp(9) : (col. 4) remark: LOOP WAS VECTORIZED. test-elemental-functions.cpp(8) : (col. 4) remark: loop was not vectorized: nonstandard loop is not a vectorization candidate.
  • 19. Obstáculos para Vetorização Acesso não-contíguo à memória "vectorization possible but seems inefficient“ Endereçamento indireto (3o exemplo): “Existence of vector dependence”
  • 20. Obstáculos para Vetorização Dependência de Dados No segundo caso, se não houver dependência (aliasing), o uso de #pragma ivdep permite “forçar” a vetorização
  • 21. Intel® Cilk™ Plus - Tasking
  • 22. Palavras-chave do Intel® Cilk™ Plus Cilk Plus adiciona 3 palavras-chave ao C/C++: _cilk_spawn _cilk_sync _cilk_for Usando #include <cilk/cilk.h>, você pode usar as palavras-chave: cilk_spawn, cilk_sync e cilk_for. O runtime do CILK Plus controla a criação de threads e seu agendamento. O pool de threads é criado antes do uso das palavras-chave do CILK Plus. Por default, o número de threads é igual ao número de núcleos (incluindo hyperthreads), mas pode ser controlado pelo usuário
  • 23. cilk_spawn e cilk_sync cilk_spawn dá ao runtime a permissão para rodar uma função-filha de forma assíncrona. – Não é criada (nem necessária) uma 2a thread! – Se não houver workers disponíveis, a função-filha será executada com uma chamada a uma função serial. – O scheduler pode “roubar” a fila da função-pai e executá-la em paralelo com a função-filha. – A função-pai não tem garantia de rodar em paralelo com a função-filha. cilk_sync aguarda a conclusão de todas as funções-filhas antes que a execução prossiga além daquele ponto. – Existem pontos de sincronismo (cilk_sync) implícitos
  • 24. Um exemplo simples Computação recursiva do número de Fibonacci: int fib(int n) { int x, y; if (n < 2) return n; x = cilk_spawn fib(n-1); y = fib(n-2); cilk_sync; return x+y; } Chamadas assíncronas devem completar antes de usar x. Execução pode continuar enquanto fib(n-1) roda.
  • 25. cilk_for Semelhante a um loop “for” regular. cilk_for (int x = 0; x < 1000000; ++x) { … } Qualquer iteração pode executar em paralelo com qualquer outra. Todas as interações completam antes do programa prosseguir. Limitações: – Limitado a uma única variável de controle. – Deve ser capaz de voltar ao início de qualquer iteração, randomicamente. – Iterações devem ser independentes umas das outras.
  • 26. Nos bastidores do cilk_for… void run_loop(first, last) { if ((last - first) < grainsize) { for (int i=first; i<last ++i) {LOOP_BODY;} } else { int mid = (last-first)/2; cilk_spawn run_loop(first, mid); run_loop(mid, last); } }
  • 27. Exemplos de cilk_for cilk_for (int x; x < 1000000; x += 2) { … } cilk_for (vector<int>::iterator x = y.begin(); x != y.end(); ++x) { … } cilk_for (list<int>::iterator x = y.begin(); x != y.end(); ++x) { … }  O contador do loop não pode ser calculado em tempo de compilação usando uma lista. (y.end() – y.begin() não é definido)  Não há acesso randômico aos elementos de uma lista. (y.begin() + n não é definido.)
  • 28. Serialização Todo programa Cilk Plus tem um equivalente serial, chamado de serialização A serialização é obtida removendo as palavras-chave cilk_spawn e cilk_sync e substituindo cilk_for por for O compilador produzirá a serialização se você compilar com /Qcilk-serialize (Windows*) ou –cilk-serialize (Linux*/OS X*) Rodar um programa com somente um worker é equivalente a rodar a serialização.
  • 29. Semântica Serial Um programa CILK Plus determinístico terá a mesma semântica se sua serialização. – Facilita a realização de testes de regressão; – Facilita o debug: – Roda com somente um núcleo – Roda serializado – Permite composição – Vantagens dos hyperobjects – Ferramentas de análise robustas (Cilk Plus SDK) – cilkscreen race detector – cilkview scalability analyzer
  • 30. Sincronismos implícitos void f() { cilk_spawn g(); cilk_for (int x = 0; x < lots; ++x) { ... } try { cilk_spawn h(); } catch (...) { ... } } Ao final de uma funcão utilizando spawn Ao final do corpo de um cilk_for (não sincroniza g()) Ao final de um bloco try contendo um spawn Antes de entrar num bloco try contendo um sync
  • 31. Composição Sincronismos implícitos são importantes para tornar cada chamada de função uma “caixa preta”. Quem chama a função não sabe (nem se importa) se a função chamada implementa spawns. A abstração serial é mantida. Que chama a função não precisa se preocupar com data races na função chamada. cilk_sync sincroniza somente funções-filhas que foram “spawned” dentro da mesma função do sync: nenhuma ação ocorre “à distância”.
  • 32. Um exemplo de soma int compute(const X& v); int main() { const std::size_t n = 1000000; extern X myArray[n]; // ... int result = 0; for (std::size_t i = 0; i < n; ++i) { result += compute(myArray[i]); } std::cout << "The result is: " << result << std::endl; return 0; }
  • 33. Somando com Intel® Cilk™ Plus int compute(const X& v); int main() { const std::size_t n = 1000000; extern X myArray[n]; // ... int result = 0; cilk_for (std::size_t i = 0; i < n; ++i) { result += compute(myArray[i]); } std::cout << "The result is: " << result << std::endl; return 0; } Race!
  • 34. Solução com Locks int compute(const X& v); int main() { const std::size_t n = 1000000; extern X myArray[n]; // ... mutex L; int result = 0; cilk_for (std::size_t i = 0; i < n; ++i) { int temp = compute(myArray[i]); L.lock(); result += temp; L.unlock(); } std::cout << "The result is: " << result << std::endl; return 0; } Problemas Sobrecarga e contenção dos Locks
  • 35. Solução com Reducer do CILK™ Plus int compute(const X& v); int main() { const std::size_t ARRAY_SIZE = 1000000; extern X myArray[ARRAY_SIZE]; // ... cilk::reducer_opadd<int> result; cilk_for (std::size_t i = 0; i < ARRAY_SIZE; ++i) { result += compute(myArray[i]); } std::cout << "The result is: " << result.get_value() << std::endl; return 0; } Declare result como reducer de soma (int) Atualizações são resolvidas automatica/e, sem races nem contenção Ao final, o valor (int) pode ser recuperado (soma)
  • 36. Biblioteca de “HyperObjects” A biblioteca de hyperobjects do Intel® Cilk™ Plus’s contém os “reducers” mais utilizados (e mais) : – reducer_list_append – reducer_list_prepend – reducer_max – reducer_max_index – reducer_min – reducer_min_index – reducer_opadd – reducer_ostream – reducer_basic_string – holder – … Você pode escrever seu próprio reducer usando cilk::monoid_base e cilk::reducer.
  • 37. Use o Intel® Cilk™ Plus Disponível em: Intel® C++ Composer XE 2011 – Incluído no Intel® Parallel Studio XE 2011 SP1 – Avaliação gratuita (30 dias) em http://software.intel.com/en-us/articles/intel- software-evaluation-center/ Patch do gcc* 4.7 (Open Source) – Obtenha em: http://cilk.com
  • 38. Material complementar Sobre Intel® Cilk™ Plus http://cilk.com Intel® Threading Building Blocks http://threadingbuildingblocks.org Suporte http://premier.intel.com Fóruns de usuários http://software.intel.com/pt-br/forums http://software.intel.com/en-us/forums/intel-cilk-plus Apresentações técnicas http://software.intel.com/en-us/articles/intel-software- development-products-technical-presentations/ (incluem mais detalhes do Cilk Plus, vetorização, Intel® Cluster Studio e muito mais!)
  • 40. • INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. • A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALL CLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITS SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS. • Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information. • The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request. • Intel processor numbers are not a measure of performance. Processor numbers differentiate features within each processor family, not across different processor families. Go to: http://www.intel.com/products/processor_number. • Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order. • Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548- 4725, or go to: http://www.intel.com/design/literature.htm • Intel, Core, Atom, Pentium, Intel inside, Sponsors of Tomorrow, Pentium, 386, 486, DX2 and the Intel logo are trademarks of Intel Corporation in the United States and other countries. • *Other names and brands may be claimed as the property of others. • Copyright ©2012 Intel Corporation. Legal Disclaimer
  • 41. Risk Factors The above statements and any others in this document that refer to plans and expectations for the second quarter, the year and the future are forward-looking statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,” “will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions also identify forward-looking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors could cause actual results to differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the important factors that could cause actual results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due to factors including changes in business and economic conditions, including supply constraints and other disruptions affecting customers; customer acceptance of Intel’s and competitors’ products; changes in customer order patterns including order cancellations; and changes in the level of inventory at customers. Uncertainty in global economic and financial conditions poses a risk that consumers and businesses may defer purchases in response to negative financial events, which could negatively affect product demand and other related matters. Intel operates in intensely competitive industries that are characterized by a high percentage of costs that are fixed or difficult to reduce in the short term and product demand that is highly variable and difficult to forecast. Revenue and the gross margin percentage are affected by the timing of Intel product introductions and the demand for and market acceptance of Intel's products; actions taken by Intel's competitors, including product offerings and introductions, marketing programs and pricing pressures and Intel’s response to such actions; and Intel’s ability to respond quickly to technological developments and to incorporate new features into its products. Intel is in the process of transitioning to its next generation of products on 22nm process technology, and there could be execution and timing issues associated with these changes, including products defects and errata and lower than anticipated manufacturing yields. The gross margin percentage could vary significantly from expectations based on capacity utilization; variations in inventory valuation, including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the timing and execution of the manufacturing ramp and associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions in the supply of materials or resources; product manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and intangible assets. The majority of Intel’s non-marketable equity investment portfolio balance is concentrated in companies in the flash memory market segment, and declines in this market segment or changes in management’s plans with respect to Intel’s investments in this market segment could result in significant impairment charges, impacting restructuring charges as well as gains/losses on equity investments and interest and other. Intel's results could be affected by adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain marketing and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and the level of revenue and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results could be affected by adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports. An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the report on Form 10-K for the year ended Dec. 31, 2011. Rev. 4/17/12