Threaded Programming Methodology Intel Software College INTEL CONFIDENTIAL

  • Slides: 59
Download presentation
Threaded Programming Methodology Intel Software College INTEL CONFIDENTIAL

Threaded Programming Methodology Intel Software College INTEL CONFIDENTIAL

Intel® Software College Objetivo Al final de este módulo • Será capaz de realizar

Intel® Software College Objetivo Al final de este módulo • Será capaz de realizar un prototipo y estimar el esfuerzo requerido paralelizar regiones que consumen tiempo Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 2

Intel® Software College Agenda Un ciclo de desarrollo genérico Caso de estudio: Generación de

Intel® Software College Agenda Un ciclo de desarrollo genérico Caso de estudio: Generación de números primos Algunos problemas de rendimiento comunes Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 3

Intel® Software College ¿Qué es paralelismo? Dos o más procesos o hilos se ejecutan

Intel® Software College ¿Qué es paralelismo? Dos o más procesos o hilos se ejecutan al mismo tiempo Paralelismo para arquitecturas con varios núcleos • Múltiples procesos – Comunicación a través de IPCs (Inter-Process Communication) • Un solo proceso, múltiples hilos – Comunicación a través de memoria compartida Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 4

Intel® Software College Ley de Amdahl Describe el límite máximo de aceleración con ejecución

Intel® Software College Ley de Amdahl Describe el límite máximo de aceleración con ejecución paralela 0. 5 0. 0 0. 5 ++ 0. 25 Tparalelo = {(1 -P) + P/n} Tserial P/2 n = número de procesadores (1 -P) … (1 -P) Tserial P n=∞ 2 P/∞ 1. 0/0. 5 1. 0/0. 75= =2. 0 1. 33 Aceleración = Tserial / Tparalelo El código serial limita la aceleración Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 5

Procesos e Hilos Intel® Software College Procesos e Hilos Stack thread Los sistemas operativos

Procesos e Hilos Intel® Software College Procesos e Hilos Stack thread Los sistemas operativos modernos cargan programas como procesos – Tiene recursos – Ejecución main() Stack thread Stack … thread Un proceso inicia ejecutando su punto de entrada como un hilo Los hilos pueden crear otros hilos dentro del proceso • Code segment Cada hilo obtiene su propio stack Todos los hilos dentro de un proceso comparten código y segmentos de datos Data segment Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 6

Intel® Software College Hilos – Beneficios y riesgos Beneficios • Mayor rendimiento y mejor

Intel® Software College Hilos – Beneficios y riesgos Beneficios • Mayor rendimiento y mejor utilización de recursos – Incluso en sistemas con un solo procesador – para esconder latencia e incrementar el tiempo de respuesta • Comunicación entre procesos a través de memoria compartida es más eficiente Riesgos • Incrementa la complejidad de la aplicación • Difícil de depurar (condiciones de concurso, interbloqueos, etc. ) Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 7

Intel® Software College Preguntas comunes cuando se paralelizan aplicaciones ¿Dónde paralelizar? ¿Cuánto tiempo lleva

Intel® Software College Preguntas comunes cuando se paralelizan aplicaciones ¿Dónde paralelizar? ¿Cuánto tiempo lleva paralelizar? ¿Cuánto esfuerzo para rediseñar se requiere? ¿Es útil paralelizar una región específica? ¿Qué tanto se espera acelerar? ¿El rendimiento va de acuerdo a mis expectativas? ¿Será escalable a más hilos/datos añadidos? ¿Qué modelo de paralelización utilizar? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 8

Intel® Software College Generación de Números Primos i 61 63 65 67 69 71

Intel® Software College Generación de Números Primos i 61 63 65 67 69 71 73 75 77 79 factor 357 3579 35 3579 bool Test. For. Prime(int val) { // let’s start checking from 3 int limit, factor = 3; limit = (long)(sqrtf((float)val)+0. 5 f); while( (factor <= limit) && (val % factor) ) factor += 2; return (factor > limit); } void Find. Primes(int start, int end) { int range = end - start + 1; for( int i = start; i <= end; i += 2 ) { if( Test. For. Prime(i) ) global. Primes[g. Primes. Found++] = i; Show. Progress(i, range); } } Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 9

Intel® Software College Actividad 1 Ejecutar la versión serial de los números primos •

Intel® Software College Actividad 1 Ejecutar la versión serial de los números primos • Buscar el directorio Prime. Single • Compilar con Intel® Parallel Composer en Visual Studio • Ejecutar algunas veces con rangos diferentes Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 10

Intel® Software College Metodología de Desarrollo Análisis • Buscar código donde se realiza cómputo

Intel® Software College Metodología de Desarrollo Análisis • Buscar código donde se realiza cómputo intensivo Diseño (Introducir Hilos) • Determinar como implementar una solución paralelizada Depurar • Detectar cualquier problema como resultado de usar hilos Afinar para mejorar el rendimiento • Lograr el mejor rendimiento en paralelo Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 11

Intel® Software College Ciclo de Desarrollo Análisis –Intel® Parallel Amplifier Diseño (Introducir Hilos) –Intel®

Intel® Software College Ciclo de Desarrollo Análisis –Intel® Parallel Amplifier Diseño (Introducir Hilos) –Intel® Performance libraries: IPP y MKL –Open. MP* (Intel® Parallel Composer) –Creción explícita de hilos (Win 32*, Pthreads*) Depuración –Intel® Parallel Inspector –Intel Debugger Afinar para mejorar el rendimiento –Intel® Parallel Amplifier Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 12

Intel® Software College Análisis de Hotspot bool Test. For. Prime(int val) { // let’s

Intel® Software College Análisis de Hotspot bool Test. For. Prime(int val) { // let’s start checking from 3 Usa Parallel Amplifier para encontrar int limit, factor = 3; los hotspots en la aplicación limit = (long)(sqrtf((float)val)+0. 5 f); while( (factor <= limit) && (val % factor)) factor ++; Usaremos el proyecto Prime. Single para> el análisis return (factor limit); • Prime. Single <inicio> <fin> } Ejemplo: . /Prime. Single 1 1000000 start, int end) void Find. Primes(int { Identifica las } // start is always odd int range = end - start + 1; for( int i = start; i <= end; i+= 2 ){ if( Test. For. Prime(i) ) global. Primes[g. Primes. Found++] = i; Show. Progress(i, range); } regiones que consumen tiempo Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 13

Intel® Software College Análisis - Call Stack • Inspeccionar el código desde el nodo

Intel® Software College Análisis - Call Stack • Inspeccionar el código desde el nodo (Test. For. Prime) • Buscar un loop paralelizar • Si no se encuentra ninguno, avanza en el call stack hasta encontrar un ciclo adecuado o llamada a función paralelizar Este es el nivel en el árbol de llamadas donde necesitamos paralelizar Usado para encontrar el nível apropiado en el árbol de llamadas paralelizar Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 14

Intel® Software College Actividad 2 Ejecuta el código con el rango de ‘ 1

Intel® Software College Actividad 2 Ejecuta el código con el rango de ‘ 1 5000000’ para obtener la medición base • Tomar nota para referencias futuras Hacer el análisis de Hotspots en el código serial • ¿Qué función se lleva la mayor parte del tiempo? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 15

Intel® Software College Metodología de Diseño de Foster De “Designing and Building Parallel Programs”

Intel® Software College Metodología de Diseño de Foster De “Designing and Building Parallel Programs” por Ian Foster Cuatro pasos: • Particionar – Dividir cómputo y datos • Comunicación – Intercambio de datos entre cómputos • Aglomeración – Agrupar tareas para mejorar rendimiento • Mapeo – Asignar tareas a procesadores/hilos Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 16

Intel® Software College Diseñando programas paralelos Particionar • Divide el problema en tareas Comunicar

Intel® Software College Diseñando programas paralelos Particionar • Divide el problema en tareas Comunicar • Determina la cantidad y el patrón de comunicación Aglomerar • Combinar tareas Mapear • Asignar tareas aglomeradas a los hilos generados Problema Tareas iniciales Comunicación Tareas combinadas Programa final Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 17

Intel® Software College Modelos de Programación Paralela Descomposición funcional • Paralelismo de tareas •

Intel® Software College Modelos de Programación Paralela Descomposición funcional • Paralelismo de tareas • Dividir el cómputo, asociarle datos • Tareas independientes del mismo problema Descomposición de datos • La misma operación ejecutando diferentes datos • Dividir datos en piezas, asociarles cómputo Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 18

Intel® Software College Métodos de descomposición Descomposición funcional Modelo atmosférico • Enfocarse a cómputo

Intel® Software College Métodos de descomposición Descomposición funcional Modelo atmosférico • Enfocarse a cómputo puede revelar la estructura en un problema Modelo de hidrología Modelo Oceano Grid reprinted with permission of Dr. Phu V. Luong, Coastal and Hydraulics Laboratory, ERDC Modelo terrestre Descomposición por dominio • • Enfocarse en la estructura de datos más grande o más frecuentemente accesada Paralelismo en los datos – La misma operación aplicada a todos los datos Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 19

Intel® Software College Descomposición en Pipeline La computación se hace en etapas independientes Descomposición

Intel® Software College Descomposición en Pipeline La computación se hace en etapas independientes Descomposición funcional • Los hilos se asignan a una etapa a computar • Línea de ensamble de automóviles Descomposición de datos • Los hilos procesan todas las etapas de una sola instancia • Un trabajador construye un auto completito Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 20

Intel® Software College Ejemplo de LAME Encoder LAME MP 3 encoder • Proyecto Open

Intel® Software College Ejemplo de LAME Encoder LAME MP 3 encoder • Proyecto Open source • Herramienta educativa El objetivo de este proyecto es • Mejorar la calidad • Mejorar la velocidad de la codificación a MP 3 Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 21

Intel® Software College Estrategia de LAME Pipeline Preludio Acústicos Extraer siguiente frame Caracterización del

Intel® Software College Estrategia de LAME Pipeline Preludio Acústicos Extraer siguiente frame Caracterización del frame Poner parámetros del encoder Analisis FFT long/short Ensamblar el filtro Tiempo Codificación Otro Agregar encabezado del frame Verificar si es correcto Escribe al disco Aplicar filtros Frame Suprimir ruidos Cuantiza y cuenta bits Barrera Jerárquica T 1 T 2 T 3 Preludio N+1 Acústicos N Preludio N+2 Preludio N+3 Acústicos N+1 Acústicos N+2 Codificación N+1 Otro N T 4 Frame N + 1 Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 22

Intel® Software College Diseño ¿Cuál es el beneficio esperado? ¿Cómo logramos esto con el

Intel® Software College Diseño ¿Cuál es el beneficio esperado? ¿Cómo logramos esto con el menor esfuerzo? Aceleración(2 P) = 100/(96/2+4) = ~1. 92 X ¿Cuánto se lleva paralelizar? ¿Cuánto esfuerzo se requiere para rediseñar? Prototipo rápido con Open. MP Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 23

Intel® Software College Open. MP Paralelismo Fork-join: • El hilo maestro se divide en

Intel® Software College Open. MP Paralelismo Fork-join: • El hilo maestro se divide en un grupo de hilos como sea necesario • El paralelismo va incrementando – Un programa secuencial evoluciona a un programa paralelo Hilo maestro Regiones Paralelas Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 24

Intel® Software College Diseño #pragma omp parallel for( int i = start; i <=

Intel® Software College Diseño #pragma omp parallel for( int i = start; i <= end; i+= 2 ){ if( Test. For. Prime(i) ) global. Primes[g. Primes. Found++] = i; Divide Open. MP Show. Progress(i, range); iteraciones de el } ciclo for Crea hilos aquí para Esta región paralela Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 25

Intel® Software College Actividad 3 Ejecuta la versión Open. MP del código • Localiza

Intel® Software College Actividad 3 Ejecuta la versión Open. MP del código • Localiza el directorio Prime. Open. MP y la solución • Compila el código • Ejecuta con ‘ 1 5000000’ para comparar – ¿Cuál es la aceleración? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 26

Intel® Software College Diseño ¿Cuál es el beneficio esperado? ¿Cómo logras esto con el

Intel® Software College Diseño ¿Cuál es el beneficio esperado? ¿Cómo logras esto con el menor esfuerzo? Aceleración de 1. 40 X (menor que 1. 92 X) ¿Cuánto tiempo se llevó paralelizar? ¿Cuánto esfuerzo se requiere para rediseñar? ¿Es la mejor aceleración posible? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 27

Intel® Software College Depuración ¿Es la implementación correcta de paralelismo? No! Los resultados son

Intel® Software College Depuración ¿Es la implementación correcta de paralelismo? No! Los resultados son diferentes cada ejecución … Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 28

Intel® Software College Depuración Intel® Parallel Inspector indica errores notorios en la paralelizacion como

Intel® Software College Depuración Intel® Parallel Inspector indica errores notorios en la paralelizacion como condiciones de concurso e interbloqueos Intel® Parallel Inspector Análisis de errores en la paralelización Dónde están los Interbloqueos o Condiciones de Concurso Colector De Datos en tiempo de ejecución Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 29

Intel® Software College Intel® Parallel Inspector (Errores en la Paralelización) • Seleccionar información en

Intel® Software College Intel® Parallel Inspector (Errores en la Paralelización) • Seleccionar información en relación condiciones de concurso e interbloqueos • Ver la descripción general de errores de la paralelización (Ti 3) • Selecciona el error e inspecciona el código Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 30

Intel® Software College Actividad 4 Usa Parallel Inspector para analizar la aplicación paralelizada •

Intel® Software College Actividad 4 Usa Parallel Inspector para analizar la aplicación paralelizada • Usa Intel Parallel Inspector para encontrar la condición de concurso que hace que el cálculo de números primos sea incorrecto • Ejecuta la aplicación • ¿Se reportan errores? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 31

Intel® Software College Depuración ¿Cuánto esfuerzo de requiere para rediseñar? Parallel Inspector solo reportó

Intel® Software College Depuración ¿Cuánto esfuerzo de requiere para rediseñar? Parallel Inspector solo reportó 3 dependencias, por lo tanto no hay mayores compliaciones ¿Cuánto nos llevará paralelizar? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 32

Intel® Software College Depuración #pragma omp parallel for( int i = start; i <=

Intel® Software College Depuración #pragma omp parallel for( int i = start; i <= end; i+= 2 ){ if( Test. For. Prime(i) ) #pragma omp critical global. Primes[g. Primes. Found++] = i; Show. Progress(i, range); Creará una sección crítica para esta referencia } #pragma omp critical { g. Progress++; Creará una sección crítica para ambas referencias percent. Done = (int)(g. Progress/range *200. 0 f+0. 5 f) } Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 33

Intel® Software College Actividad 5 Modifica y ejecuta la versión de Open MP del

Intel® Software College Actividad 5 Modifica y ejecuta la versión de Open MP del código • Añade pragmas de regiones críticas al código • Compila el código • Ejecuta Parallel Inspector (Errores de Paralelización) – Si los errores siguen presentes, haz las correcciones apropiadas al código y ejecuta de nuevo en Parallel Inspector • Ejecuta con ‘ 1 5000000’ para comparar – Compila y ejecuta sin debugging – ¿Cuál es la aceleración? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 34

Intel® Software College Depuración Respuesta correcta, pero el rendimiento bajo al ~1. 33 X

Intel® Software College Depuración Respuesta correcta, pero el rendimiento bajo al ~1. 33 X 1. 33 ¿Es lo mejor que podemos esperar de este algoritmo? No! De acuerdo a la Ley de Amdahl, podemos esperar una aceleración cerca de 1. 9 X Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 35

Intel® Software College Problemas comunes de rendimiento Sobrecarga en paralelo • Dada por la

Intel® Software College Problemas comunes de rendimiento Sobrecarga en paralelo • Dada por la creación de hilos, planificación… Sincronización • Datos globales excesivos, contención de los mismos objetos de sincronización Carga desbalanceada • Distribución no adecuada del trabajo en paralelo Granularidad • No hay suficiente trabajo paralelo Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 36

Intel® Software College Afinando para mejorar el rendimiento • Parallel Amplifier (Locks y Waits)

Intel® Software College Afinando para mejorar el rendimiento • Parallel Amplifier (Locks y Waits) apunta a cuellos de botella en el rendimiento en aplicaciones con hilos Intel® Parallel Amplifier Locks & Waits Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 37

Intel® Software College Parallel Amplifier/ Locks y Waits • La gráfica muestra una porción

Intel® Software College Parallel Amplifier/ Locks y Waits • La gráfica muestra una porción de tiempo significativa en condición ociosa como resultado de la sección crítica • Find. Primes() y Show. Progress() están significativamente impactadas por el tiempo ocioso ocurriendo en la sección crítica Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 38

Intel® Software College Parallel Amplifier/ Locks y Waits • • Show. Progress() consume 558/657

Intel® Software College Parallel Amplifier/ Locks y Waits • • Show. Progress() consume 558/657 (85%) del tiempo permaneciendo ocioso en una sección crítica Haz Double Click en Show. Progress() en la sección crítica más larga para ver el código fuente Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 39

Intel® Software College Parallel Amplifier/ Resumen • El tiempo transcurrido muestra. 571 sec •

Intel® Software College Parallel Amplifier/ Resumen • El tiempo transcurrido muestra. 571 sec • Tiempo de espera/ Núcleos = 1. 87/4 =. 47 sec • Esperando el 82% del tiempo transcurrido en una sección crítica • La mayoría del tiempo 1 núcleo y ocasionalmente están ocupados 2 Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 40

Intel® Software College Parallel Amplifier/ Concurrencia • Concurrencia (Function –Caller Function Tree) • Show.

Intel® Software College Parallel Amplifier/ Concurrencia • Concurrencia (Function –Caller Function Tree) • Show. Progress es llamada de Find. Primes y representa mayormente la razón por la cual la concurrencia es pobre Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 41

Intel® Software College Parallel Amplifier/ Concurrencia • Concurrencia (Thread –Function –Caller Function Tree) •

Intel® Software College Parallel Amplifier/ Concurrencia • Concurrencia (Thread –Function –Caller Function Tree) • Esta pantalla muestra como cada hilo contribuye al problema de concurrencia • Expandiendo cualquier hilo las funciones que más contibuyen Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 42

Intel® Software College Rendimiento • Double Click en Show. Progress en la segunda sección

Intel® Software College Rendimiento • Double Click en Show. Progress en la segunda sección crítica más larga • Esta implementación tiene llamadas de sincronización implícita - printf • Esto limita la mejora del rendimiento debido a cambios de contexto resultantes De regreso a la etapa de diseño Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 43

Intel® Software College Actividad 6 Usar Parallel Amplifier para analizar la aplicación con hilos

Intel® Software College Actividad 6 Usar Parallel Amplifier para analizar la aplicación con hilos • Usar la herramienta Parallel Amplifier (Análisis de Locks y Waits) • Identifica los waits y locks que más contribuyen Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 44

Intel® Software College Rendimiento ¿Es esto mucha contención esperada? void Show. Progress( int val,

Intel® Software College Rendimiento ¿Es esto mucha contención esperada? void Show. Progress( int val, int range ) ) { { int percent. Done; g. Progress++; static int last. Percent. Done = 0; percent. Done = (int)((float)g. Progress/(float)range*200. 0 f+0. 5 f); #pragma omp critical } El } { if(g. Progress++; percent. Done % 10 == 0 ) printf("bb%3 d%%", percent. Done); percent. Done = (int)((float)g. Progress/(float)range*200. 0 f+0. 5 f); } if( percent. Done % 10 == 0 && last. Percent. Done < percent. Done / 10){ printf("bb%3 d%%", percent. Done); last. Percent. Done++; algoritmo tiene muchas más actualizaciones a variables que las } necesitadas para mostrar el progreso Este cambio debe arreglar el problema de contención Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 45 10

Intel® Software College Diseño Meta • Elimina la contención debido a la sincronización implícita

Intel® Software College Diseño Meta • Elimina la contención debido a la sincronización implícita ¡La aceleración es 2. 32 X ! ¿Es correcto? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 46

Intel® Software College Rendimiento Nuestra medida base original tenía la actualización del algoritmo de

Intel® Software College Rendimiento Nuestra medida base original tenía la actualización del algoritmo de progreso “defectuoso” ¿Es lo mejor que podemos esperar de este algoritmo? ¡La aceleración actual es 1. 40 X (<<1. 9 X)! Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 47

Intel® Software College Actividad 7 Modifica la función Show. Progress (en la versiones serial

Intel® Software College Actividad 7 Modifica la función Show. Progress (en la versiones serial y Open. MP) para solo mostrar la salida necesaria if( percent. Done % 10 == 0 && last. Percent. Done < percent. Done){ printf("bb%3 d%%", percent. Done); last. Percent. Done += 10; } • Recompila y ejecuta el programa – Asegurarse que no se están usando banderas de instrumentación • ¿Cuál es la aceleración con respecto a la versión serial? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 48

Intel® Software College Revisando el Rendimiento • • • Locks y Waits – Antes

Intel® Software College Revisando el Rendimiento • • • Locks y Waits – Antes y Después de cambiar a la función printf En la versión más rápida – el printf es llamado ~ 10 x menos veces last. Percent. Done < percent. Done / 10 Locks y Waits “self wait count” y “poor” muestran una diferencia significativa entre versiones Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 49

Intel® Software College Revisando el Rendimiento Veamos los Locks de Open. MP… void Find.

Intel® Software College Revisando el Rendimiento Veamos los Locks de Open. MP… void Find. Primes(int start, int end) { { // start is always odd int range = end - start + 1; #pragma omp parallel for for( int i = start; i <= end; i += 2 ) { { Hay un lock en if( Test. For. Prime(i) ) un ciclo #pragma omp critical global. Primes[Interlocked. Increment(&g. Primes. Found)] = i; global. Primes[g. Primes. Found++] = i; } } Show. Progress(i, range); Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 50

Intel® Software College Revisando el Rendimiento Veamos el segundo lock void Show. Progress( int

Intel® Software College Revisando el Rendimiento Veamos el segundo lock void Show. Progress( int val, int range ) { int percent. Done; long percent. Done, local. Progress; static int last. Percent. Done = 0; Este es un lock que static int last. Percent. Done = 0; #pragma omp critical está siendo llamado {local. Progress = Interlocked. Increment(&g. Progress); dentro de un ciclo g. Progress++; percent. Done = (int)((float)local. Progress/(float)range*200. 0 f+0. 5 f); percent. Done = (int)((float)g. Progress/(float)range*200. 0 f+0. 5 f); } if( percent. Done % 10 == 0 && last. Percent. Done < percent. Done / 10){ printf("bbbb%3 d%%", percent. Done); last. Percent. Done++; } } Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 51

Intel® Software College Actividad 8 Modifica las regiones críticas de Open. MP para usar

Intel® Software College Actividad 8 Modifica las regiones críticas de Open. MP para usar Interlocked. Increment en vez de • Re-compila y ejecuta el programa ´¿Cuál es la aceleración con respecto a la versión serial? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 52

Intel® Software College Análisis del balanceo de carga • Usa el análisis de concurrencia

Intel® Software College Análisis del balanceo de carga • Usa el análisis de concurrencia de Parallel Amplifier • Selecciona “Thread –Function -Caller Function Tree” • Observa que los 4 hilos hacen cantidades de trabajo desiguales Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 53

Intel® Software College Arreglando el Desbalanceo de Carga Distribuye el trabajo de manera más

Intel® Software College Arreglando el Desbalanceo de Carga Distribuye el trabajo de manera más uniforme void Find. Primes(int start, int end) { // start is always odd int range = end - start + 1; #pragma omp parallel for schedule(static, 8) for( int i = start; i <= end; i += 2 ) { if( Test. For. Prime(i) ) global. Primes[Interlocked. Increment(&g. Primes. Found)] = i; Show. Progress(i, range); } } La aceleración lograda es 1. 68 X Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 54

Intel® Software College Actividad 9 Modifica el código para un mejor balanceo de carga

Intel® Software College Actividad 9 Modifica el código para un mejor balanceo de carga • Añade la cláusula schedule (static, 8) al pragma de Open. MP parallel for • Re-compila y ejecuta el programa • ¿Cuál es la aceleración comparada con la versión serial? Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 55

Intel® Software College Análisis final de balanceo de carga La aceleración lograda es 1.

Intel® Software College Análisis final de balanceo de carga La aceleración lograda es 1. 80 X Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 56

Intel® Software College Análisis Comparativo Paralelizar aplicaciones requiere varias iteraciones a través del ciclo

Intel® Software College Análisis Comparativo Paralelizar aplicaciones requiere varias iteraciones a través del ciclo de desarrollo de software Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 57

Metodología de paralelización Lo que se Cubrió Intel® Software College Cuatro pasos del ciclo

Metodología de paralelización Lo que se Cubrió Intel® Software College Cuatro pasos del ciclo de desarrollo para escribir aplicaciones paralelas desde el código serial y las herramientas de Intel® para soportar cada paso • • Análisis Diseño (Introducir Hilos) Depurar para la correctud Afinar el rendimiento Las aplicaciones paralelas requieren múltiples iteraciones de diseño, depuración y afinación de rendimiento Usar las herramientas para mejorar productividad Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 58

Intel® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the

Intel® Software College Copyright © 2008, Intel Corporation. All rights reserved. Intel and the Intel logo are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States or other countries. * Other brands and names are the property of their respective owners. 59