Железные счётчики на страже производительности
-
Upload
sergey-kuksenko -
Category
Software
-
view
839 -
download
0
Transcript of Железные счётчики на страже производительности
The following is intended to outline our general product direction. Itis intended for information purposes only, and may not beincorporated into any contract. It is not a commitment to deliver anymaterial, code, or functionality, and should not be relied upon inmaking purchasing decisions. The development, release, and timingof any features or functionality described for Oracle’s productsremains at the sole discretion of Oracle.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 2/65
Глава первая
Очень краткое введение вМетодологию Оптимизации
Производительности,«Что-Где-Как» и «Сверху-Вниз»,
а также о роли «железных» счетчиков
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 3/65
3 магических вопроса
Что? ⇒ Где? ⇒ Как?
∙ Что мешает работать быстрее? (monitoring)
∙ Где это находится? (profiling)
∙ Как это исправить? (tuning/optimizing)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
3 магических вопроса
Что?
⇒ Где? ⇒ Как?
∙ Что мешает работать быстрее? (monitoring)
∙ Где это находится? (profiling)
∙ Как это исправить? (tuning/optimizing)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
3 магических вопроса
Что? ⇒ Где?
⇒ Как?
∙ Что мешает работать быстрее? (monitoring)
∙ Где это находится? (profiling)
∙ Как это исправить? (tuning/optimizing)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
3 магических вопроса
Что? ⇒ Где? ⇒ Как?
∙ Что мешает работать быстрее? (monitoring)
∙ Где это находится? (profiling)
∙ Как это исправить? (tuning/optimizing)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
Сверху-Вниз
∙ Системный уровень– OS, сеть, диск, процессор/память
∙ Уровень JVM– GC/Heap, JIT, classloading
∙ Уровень приложения– алгоритм, многопоточность, синхронизация, API
∙ Микроархитектурный уровень– caches, code/data alignment, pipeline stalls
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 5/65
Mindmap
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 6/65
Mindmap
http://j.mp/PerfMindMap
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 7/65
Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .⇓
∙ Много %irq, %soft ⇒ . . .⇓
∙ Много %iowait ⇒ . . .⇓
∙ Много %idle ⇒ . . .⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .⇓
∙ Много %irq, %soft ⇒ . . .⇓
∙ Много %iowait ⇒ . . .⇓
∙ Много %idle ⇒ . . .⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .⇓
∙ Много %irq, %soft ⇒ . . .⇓
∙ Много %iowait ⇒ . . .⇓
∙ Много %idle ⇒ . . .⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .⇓
∙ Много %irq, %soft ⇒ . . .⇓
∙ Много %iowait ⇒ . . .⇓
∙ Много %idle ⇒ . . .⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .⇓
∙ Много %irq, %soft ⇒ . . .⇓
∙ Много %iowait ⇒ . . .⇓
∙ Много %idle ⇒ . . .⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .⇓
∙ Много %irq, %soft ⇒ . . .⇓
∙ Много %iowait ⇒ . . .⇓
∙ Много %idle ⇒ . . .⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
Глава вторая
О высоком.
О высокой загрузке процессора,
а также
главный вопрос жизни и всего остального
«Кто виноват?»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 9/65
CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?
– Как часто OS ставит процессы на исполнение.
Профилирование?
Профилирование покажет«ГДЕ» программа проводит время,без ответа на вопрос «ПОЧЕМУ».
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?– Как часто OS ставит процессы на исполнение.
Профилирование?
Профилирование покажет«ГДЕ» программа проводит время,без ответа на вопрос «ПОЧЕМУ».
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?– Как часто OS ставит процессы на исполнение.
Профилирование?
Профилирование покажет«ГДЕ» программа проводит время,без ответа на вопрос «ПОЧЕМУ».
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?– Как часто OS ставит процессы на исполнение.
Профилирование?
Профилирование покажет«ГДЕ» программа проводит время,без ответа на вопрос «ПОЧЕМУ».
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
Кто виноват?
Сложная микроархитектура современных CPU:
e.g.Sergey Kuksenko«Quantum Performance Effects»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 11/65
Кто виноват?
Сложная микроархитектура современных CPU:
e.g.Sergey Kuksenko«Quantum Performance Effects»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 11/65
Кто виноват?
Сложная микроархитектура современных CPU:
∙ Плохой алгоритм ⇒ 100% CPU
∙ Ждем данные из памяти ⇒ 100% CPU
∙ Откат из-за непредсказанного перехода ⇒ 100% CPU
∙ Сложные и дорогие операции ⇒ 100% CPU
∙ Не хватает ILP ⇒ 100% CPU
∙ и т.д. ⇒ 100% CPU
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 12/65
Глава третья
«Железные» счетчики
HWC, PMU - WTF?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 13/65
PMU: Performance Monitoring Unit
Performance Monitoring Unit - это встроенный хардверныйпрофайлер внутри процессора.
Устройство PMU (за 21 день) :
«Железные» счетчики (Hardware counters, HWC) считаютпроисходящие события (Performance monitoring events)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 14/65
PMU: Performance Monitoring Unit
Performance Monitoring Unit - это встроенный хардверныйпрофайлер внутри процессора.
Устройство PMU (за 21 день) :
«Железные» счетчики (Hardware counters, HWC) считаютпроисходящие события (Performance monitoring events)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 14/65
События
Читаем документацию от производителя! (e.g. 2 страницы из 32)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 15/65
События
Проблемы:
∙ Тысяча их!
∙ Требуют знания микроархитектуры∙ Платформозависимые
– сильно различаются у разных производителей CPU– могут сильно меняться у одного производителя при смене
микроархитектуры
∙ Как с ними вообще работать?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 16/65
HWC
HWC имеют два режима работы:∙ Counting mode
– if (случилось событие) ++counter;
– общая диагностика (ответ на вопрос «ЧТО»)
∙ Sampling mode– if (случилось событие)
if (++counter < threshold ) INTERRUPT;
– позволяет профилировать (ответ на вопрос «ГДЕ»)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 17/65
HWC: Проблемы
Событий много, счетчиков мало(e.g. Nehalem: 3 fixed HWC, 4 programmable)
∙ «multiple-running» (с разными событиями)– повторяемость приложения
∙ multiplexing (если тулы позволяют)– стабильность приложения (steady state)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 18/65
HWC: Проблемы (cont.)
Sampling mode:
∙ «instruction skid»(невозможность точного связывания события и инструкции)
∙ Uncore events(e.g. у нас общий L3 cache на несколько ядер)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 19/65
HWC: использование
∙ валидация железа
∙ анализ производительности
∙ run-time tuning (e.g. JRockit, etc.)
∙ security attacks и защита от них
∙ test code coverage
∙ etc.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 20/65
HWC: использование
∙ валидация железа
∙ анализ производительности
∙ run-time tuning (e.g. JRockit, etc.)
∙ security attacks и защита от них
∙ test code coverage
∙ etc.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 20/65
HWC: tools
∙ Oracle Solaris Studio Performance Analyzer
∙ perf (perf_events) (http://perf.wiki.kernel.org)∙ JMH
– perf mode– perfnorm mode (perf нормализованный на количество операций)– perfasm mode (perf + -XX:+PrintAssembly)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 21/65
HWC: tools(cont.)
∙ AMD CodeXL
∙ Intel Vtune Amplifier XE
∙ etc...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 22/65
События perf_events (e.g.)
∙ cycles
∙ instructions
∙ cache-references
∙ cache-misses
∙ branches
∙ branch-misses
∙ bus-cycles
∙ ref-cycles
∙ dTLB-loads
∙ dTLB-load-misses
∙ L1-dcache-loads
∙ L1-dcache-load-misses
∙ L1-dcache-stores
∙ L1-dcache-store-misses
∙ LLC-loads
∙ LLC-load-misses
∙ etc...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 23/65
События Oracle Studio (e.g.)
∙ cycles
∙ insts
∙ branch-instruction-retired
∙ branch-misses-retired
∙ dtlbm
∙ l1h
∙ l1m
∙ l2h
∙ l2m
∙ l3h
∙ l3m
∙ etc...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 24/65
Глава четвертая
Я собрал данные HWC, и?или
Введение в микроархитектурный
анализ производительности
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 25/65
Время работы
𝑡𝑖𝑚𝑒 = 𝑐𝑦𝑐𝑙𝑒𝑠𝑓𝑟𝑒𝑞𝑢𝑒𝑛𝑐𝑦
Оптимизация это
уменьшение количества тактов (cycles)!⋆
⋆все остальное - overclockingCopyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 26/65
ГУМ
Главное Уравнение Микроархитектуры:
𝑐𝑦𝑐𝑙𝑒𝑠 = 𝑃𝑎𝑡ℎ𝐿𝑒𝑛𝑔𝑡ℎ * 𝐶𝑃𝐼 = 𝑃𝑎𝑡ℎ𝐿𝑒𝑛𝑔𝑡ℎ * 1𝐼𝑃𝐶
∙ PathLength - количество инструкций
∙ CPI - cycles per instruction
∙ IPC - instructions per cycle
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 27/65
𝑃𝑎𝑡ℎ𝐿𝑒𝑛𝑔𝑡ℎ * 𝐶𝑃𝐼
∙ PathLength - мера эффективности алгоритма(чем меньше, тем лучше)
∙ CPI - мера эффективности работы CPU(чем меньше, тем лучше)
– 𝐶𝑃𝐼 = 4 – плохо!– 𝐶𝑃𝐼 = 1
∙ Nehalem – сойдет!
∙ SandyBridge и позже – плоховатенько!
– 𝐶𝑃𝐼 = 0.4 – хорошо!– 𝐶𝑃𝐼 = 0.2 – идеально!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/65
Что делать?
∙ низкий CPI– уменьшаем PathLength – «улучшаем эффективность алгоритма»
∙ большой CPI ⇒ stalls– memory stalls – «улучшаем эффективность структур данных»– branch stalls – «улучшаем логику передачи управления»– instruction dependency – «разрываем зависимости по данным»– long latency ops – «заменяем на полегче»– и т.д.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 29/65
Проблемы с CPI?
Нам нужна классификация проблем!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 30/65
Memory bound
∙ dTLB misses
∙ L1,L2,L3,...,LN misses
∙ NUMA (чужая память)
∙ memory bandwidth
∙ sharing (false/true)
∙ cache line split (не бывает в Java, почти)
∙ store forwarding(маловероятно, да и все равно не исправить на Java уровне)
∙ 4k aliasing (попробуй поймать)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 31/65
Core bound
∙ long latency operations (DIV, SQRT)
∙ FP assist (floating points denormal, NaN, inf)
∙ bad speculation (вызывается непредсказанным переходом)
∙ port saturation (нам не нужно)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 32/65
Front-End bound
∙ iTLB miss
∙ iCache miss
∙ branch mispredict
∙ LSD (loop stream decoder)
Можно решить, только если залезть в исходники HotSpot
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 33/65
Примеры
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 34/65
Пример первый
Некий «большой» индустриальныйJava бенчмарк
Который до сих пор снится по ночам многим
Java Performance инженерам
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 35/65
Пример 1: perf stat -d
880851.993237 task -clock (msec)
39,318 context -switches
437 cpu -migrations
7,931 page -faults
2 ,275 ,263 ,113 ,376 cycles
1 ,226 ,299 ,634 ,877 instructions # 0.54 insns per cycle
229 ,500 ,265 ,931 branches # 260.544 M/sec
4 ,620 ,666 ,169 branch -misses # 2.01% of all branches
338 ,169 ,489 ,902 L1-dcache -loads # 383.912 M/sec
37 ,937 ,596 ,505 L1-dcache -load -misses # 11.22% of all L1-dcache hits
25 ,232 ,434 ,666 LLC -loads # 28.645 M/sec
7 ,307 ,884 ,874 L1-icache -load -misses # 0.00% of all L1 -icache hits
337 ,230 ,278 ,697 dTLB -loads # 382.846 M/sec
6 ,094 ,356 ,801 dTLB -load -misses # 1.81% of all dTLB cache hits
12 ,210 ,841 ,909 iTLB -loads # 13.863 M/sec
431 ,803 ,270 iTLB -load -misses # 3.54% of all iTLB cache hits
301.557213044 seconds time elapsed
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 36/65
Пример 1: обработанный руками perf stat -d
IPC 0.54cycles ×1012 2.28instructions ×1012 1.23L1-dcache-loads ×109
2
338L1-dcache-load-misses ×109
2
38LLC-loads ×109
2
25dTLB-loads ×109
2
337dTLB-load-misses ×109
2
6iTLB-loads ×109
2
12iTLB-loads-misses ×106
2
432
Посчитаем:
4
2
× (338× 109
2
)+12× ((38− 25)× 109
2
)+36× (25× 109
2
) ≈2.4× 1012 cycles ???
Проблемы?
Supersc
alarin Act
ion!
Проблемы!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
Пример 1: обработанный руками perf stat -d
IPC 0.54cycles ×1012 2.28instructions ×1012 1.23L1-dcache-loads ×109
2
338L1-dcache-load-misses ×109
2
38LLC-loads ×109
2
25dTLB-loads ×109
2
337dTLB-load-misses ×109
2
6iTLB-loads ×109
2
12iTLB-loads-misses ×106
2
432
Посчитаем:
4
2
× (338× 109
2
)+12× ((38− 25)× 109
2
)+36× (25× 109
2
) ≈2.4× 1012 cycles ???
Проблемы?
Supersc
alarin Act
ion!
Проблемы!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
Пример 1: обработанный руками perf stat -d
IPC 0.54cycles ×1012 2.28instructions ×1012 1.23L1-dcache-loads ×109
2
338L1-dcache-load-misses ×109
2
38LLC-loads ×109
2
25dTLB-loads ×109
2
337dTLB-load-misses ×109
2
6iTLB-loads ×109
2
12iTLB-loads-misses ×106
2
432
Посчитаем:
4
2
× (338× 109
2
)+12× ((38− 25)× 109
2
)+36× (25× 109
2
) ≈2.4× 1012 cycles ???
Проблемы?
Supersc
alarin Act
ion!
Проблемы!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
Пример 1: обработанный руками perf stat -d
IPC 0.54cycles ×1012 2.28instructions ×1012 1.23L1-dcache-loads ×109
2
338L1-dcache-load-misses ×109
2
38LLC-loads ×109
2
25dTLB-loads ×109
2
337dTLB-load-misses ×109
2
6iTLB-loads ×109
2
12iTLB-loads-misses ×106
2
432
Посчитаем:
4
2
× (338× 109
2
)+12× ((38− 25)× 109
2
)+36× (25× 109
2
) ≈2.4× 1012 cycles ???
Проблемы?
Supersc
alarin Act
ion!
Проблемы!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
Пример 1: обработанный руками perf stat -d
IPC 0.54cycles ×1012 2.28instructions ×1012 1.23L1-dcache-loads ×109
2
338L1-dcache-load-misses ×109
2
38LLC-loads ×109
2
25dTLB-loads ×109
2
337dTLB-load-misses ×109
2
6iTLB-loads ×109
2
12iTLB-loads-misses ×106
2
432
Посчитаем:
4
2
× (338× 109
2
)+12× ((38− 25)× 109
2
)+36× (25× 109
2
) ≈2.4× 1012 cycles ???
Проблемы?
Supersc
alarin Act
ion!
Проблемы!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
Пример 1: dTLB misses
TLB = Translation Lookaside Buffer
∙ Кэш транслятора виртуальных адресов в физические
∙ Каждое обращение к памяти – обращение к TLB
∙ TLB miss может стоить сотни тактов
Как проверить:
∙ dtlb_load_misses_miss_causes_a_walk
∙ dtlb_load_misses_walk_duration
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 38/65
Пример 1: dTLB misses
TLB = Translation Lookaside Buffer
∙ Кэш транслятора виртуальных адресов в физические
∙ Каждое обращение к памяти – обращение к TLB
∙ TLB miss может стоить сотни тактов
Как проверить:
∙ dtlb_load_misses_miss_causes_a_walk
∙ dtlb_load_misses_walk_duration
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 38/65
Пример 1: dTLB misses
IPC 0.54cycles ×1012 2.28instructions ×1012 1.23L1-dcache-loads ×109
2
338L1-dcache-load-misses ×109
2
38LLC-loads ×109
2
25dTLB-loads ×109
2
337dTLB-load-misses ×109
2
6iTLB-loads ×109
2
12iTLB-loads-misses ×106
2
432dTLB-walks-duration ×109
2
296
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 39/65
Пример 1: dTLB misses
Что делать:∙ LargePages (Huge pages)
∙ попытаться уменьшить «Working Set»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 40/65
Пример 1: -XX:+UseLargePages
baseline raw
normalized
IPC 0.54 0.64
0.64
cycles ×1012 2.28 2.28
1.9
instructions ×1012 1.23 1.46
1.22
L1-dcache-loads ×109
2
338 401
334
L1-dcache-load-misses ×109
2
38 38
32
LLC-loads ×109
2
25 25
21
dTLB-loads ×109
2
337 401
334
dTLB-load-misses ×109
2
6 0.24
0.20
iTLB-loads-misses ×106
2
432 27
23
dTLB-walks-duration ×109
2
296 2.6
2.2
Ускорение – 20%Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 41/65
Пример 1: -XX:+UseLargePages
baseline raw normalizedIPC 0.54 0.64 0.64cycles ×1012 2.28 2.28 1.9instructions ×1012 1.23 1.46 1.22L1-dcache-loads ×109
2
338 401 334L1-dcache-load-misses ×109
2
38 38 32LLC-loads ×109
2
25 25 21dTLB-loads ×109
2
337 401 334dTLB-load-misses ×109
2
6 0.24 0.20iTLB-loads-misses ×106
2
432 27 23dTLB-walks-duration ×109
2
296 2.6 2.2Ускорение – 20%Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 41/65
Пример второй
Мы нашли горячий методили
О⋆ применимости алгоритмических оптимизаций
⋆О-обычноеCopyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 42/65
Пример 2: Very Hot Code
public Matrix multiply(Matrix other) {
int size = data.length;
Matrix result = new Matrix(size);
int [][] R = result.data;
int [][] A = this.data;
int [][] B = other.data;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int s = 0;
for (int k = 0; k < size; k++) {
s += A[i][k] * B[k][j];
}
R[i][j] = s;
}
}
return result;
}
𝑂(𝑁3)⋆
⋆O-большое
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 43/65
Пример 2: Very Hot Code
public Matrix multiply(Matrix other) {
int size = data.length;
Matrix result = new Matrix(size);
int [][] R = result.data;
int [][] A = this.data;
int [][] B = other.data;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int s = 0;
for (int k = 0; k < size; k++) {
s += A[i][k] * B[k][j];
}
R[i][j] = s;
}
}
return result;
}
𝑂(𝑁3)⋆
⋆O-большоеCopyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 43/65
Пример 2: "Ok Google"
𝑂(𝑁2.81)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 44/65
Пример 2: Very Hot Code
N multiply strassen
32 33 𝜇𝑠64 252 𝜇𝑠128 3019 𝜇𝑠 2119 𝜇𝑠256 32 𝑚𝑠 15 𝑚𝑠512 488 𝑚𝑠 111 𝑚𝑠1024 3270 𝑚𝑠 785 𝑚𝑠2048 32 𝑠 6 𝑠4096 309 𝑠 42 𝑠8192 2611⋆ 𝑠 293 𝑠
time/op
⋆43 min 31 secCopyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 45/65
А если мы пойдем другим путем?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 46/65
Пример 2: JMH, -prof perfnorm, N=256
per multiplication per iterationCPI 1.06cycles 146× 106 8.7instructions 137× 106 8.2L1-loads 68× 106 4L1-load-misses 33× 106 2L1-stores 0.56× 106
L1-store-misses 38357LLC-loads 26× 106 1.6LLC-stores 11595
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 47/65
Пример 2: Very Hot Code
public Matrix multiply(Matrix other) {
int size = data.length;
Matrix result = new Matrix(size);
int [][] R = result.data;
int [][] A = this.data;
int [][] B = other.data;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int s = 0;
for (int k = 0; k < size; k++) {
s += A[i][k] * B[k][j] ;
}
R[i][j] = s;
}
}
return result;
}
L1-dcache-load-misses
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 48/65
Пример 2: Very Hot Code
public Matrix multiply(Matrix other) {
int size = data.length;
Matrix result = new Matrix(size);
int [][] R = result.data;
int [][] A = this.data;
int [][] B = other.data;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
int s = 0;
for (int k = 0; k < size; k++) {
s += A[i][k] * B[k][j] ;
}
R[i][j] = s;
}
}
return result;
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 48/65
Пример 2: Very Hot Code
public Matrix multiplyIKJ(Matrix other) {
int size = data.length;
Matrix result = new Matrix(size);
int [][] R = result.data;
int [][] A = this.data;
int [][] B = other.data;
for (int i = 0; i < size; i++) {
for (int k = 0; k < size; k++) {
int aik = A[i][k];
for (int j = 0; j < size; j++) {
R[i][j] += aik * B[k][j];
}
}
}
return result;
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 49/65
Пример 2: Very Hot Code
IJK IKJN multiply strassen multiply
strassen
32 33 𝜇𝑠 13 𝜇𝑠64 252 𝜇𝑠 80 𝜇𝑠128 3019 𝜇𝑠 2119 𝜇𝑠 464 𝜇𝑠256 32 𝑚𝑠 15 𝑚𝑠 4 𝑚𝑠512 488 𝑚𝑠 111 𝑚𝑠 29 𝑚𝑠
25 𝑚𝑠
1024 3270 𝑚𝑠 785 𝑚𝑠 369 𝑚𝑠
192 𝑚𝑠
2048 32 𝑠 6 𝑠 3.4 𝑠
1.4 𝑠
4096 309 𝑠 42 𝑠 25 𝑠
10 𝑠
8192 2611 𝑠 293 𝑠 210 𝑠
73 𝑠
time/opCopyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 50/65
Пример 2: Very Hot Code
IJK IKJN multiply strassen multiply strassen
32 33 𝜇𝑠 13 𝜇𝑠64 252 𝜇𝑠 80 𝜇𝑠128 3019 𝜇𝑠 2119 𝜇𝑠 464 𝜇𝑠256 32 𝑚𝑠 15 𝑚𝑠 4 𝑚𝑠512 488 𝑚𝑠 111 𝑚𝑠 29 𝑚𝑠 25 𝑚𝑠1024 3270 𝑚𝑠 785 𝑚𝑠 369 𝑚𝑠 192 𝑚𝑠2048 32 𝑠 6 𝑠 3.4 𝑠 1.4 𝑠4096 309 𝑠 42 𝑠 25 𝑠 10 𝑠8192 2611 𝑠 293 𝑠 210 𝑠 73 𝑠
time/opCopyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 50/65
Пример 2: JMH, -prof perfnorm, N=256
IJK IKJmultiply iteration multiply iteration
CPI 1.06 0.51cycles 146× 106 8.7 9.7× 106 0.6instructions 137× 106 8.2 19× 106 1.1L1-loads 68× 106 4 5.4× 106 0.3L1-load-misses 33× 106 2 1.1× 106 0.1L1-stores 0.56× 106 2.7× 106 0.2L1-store-misses 38357 8959LLC-loads 26× 106 1.6 0.3× 106
LLC-stores 11595 3532
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 51/65
Пример 2: Дополнительные плюшки!
cycles insts
...
6.42% 5.54% 0x00007ff6591d20c5: vmovdqu %ymm1 ,0x10(%r14 ,%rbx ,4) ;* iastore
9.49% 11.91% 0x00007ff6591d20cc: add $0x8 ,%ebx ;*iinc
0.15% 0.05% 0x00007ff6591d20cf: cmp %r11d ,%ebx
0x00007ff6591d20d2: jl 0x00007ff6591d20b2 ;* if_icmpge
...
Векторизация (SSE/AVX)!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 52/65
Пример 2: Дополнительные плюшки!
cycles insts
...
6.42% 5.54% 0x00007ff6591d20c5: vmovdqu %ymm1 ,0x10(%r14 ,%rbx ,4) ;* iastore
9.49% 11.91% 0x00007ff6591d20cc: add $0x8 ,%ebx ;*iinc
0.15% 0.05% 0x00007ff6591d20cf: cmp %r11d ,%ebx
0x00007ff6591d20d2: jl 0x00007ff6591d20b2 ;* if_icmpge
...
Векторизация (SSE/AVX)!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 52/65
Пример третий
«++ на оба ваши треда»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 53/65
Пример 3: False Sharing
@State(Scope.Group)
public static class StateBaseline {
int field0;
int field1;
}
@Benchmark
@Group("baseline")
public int justDoIt(StateBaseline s) {
return s.field0 ++;
}
@Benchmark
@Group("baseline")
public int doItFromOtherThread(StateBaseline s) {
return s.field1 ++;
}
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 54/65
Пример 3: измерим
что общего sharing paddedSame Core (HT) L1 9.5 4.9Diff Cores (within socket) L3 (LLC) 10.6 2.8Diff Sockets ничего 18.2 2.8
average time, ns/op
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 55/65
Пример 3: соберем HWC
Данные нормализованы на 103 операций
d
Same Core Diff Cores Diff Socketssharing padded sharing padded sharing padded
CPI 1.3 0.7 1.4 0.4 1.7 0.4cycles 33130 17536 36012 9163 46484 9608instructions 26418 25865 26550 25747 26717 25768L1-loads 12593 9467 9696 8973 9672 9016L1-load-misses 10 5 12 4 33 3L1-stores 4317 7838 7433 4069 6935 4074L1-store-misses 5 2 161 2 55 1
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 56/65
Пример 3: соберем HWC (продолжение)
Данные нормализованы на 103 операций
d
Same Core Diff Cores Diff Socketssharing padded sharing padded sharing padded
LLС-loads 4 3 58 1 32 1LLC-load-misses 1 1 53 ≈0 35 ≈0LLC-stores 1 1 183 ≈0 49 ≈0LLC-store-misses 1 ≈0 182 ≈0 48 ≈0
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 57/65
Пример 3: На честном слове и на одном ядре
для одного ядра нам нужно считатьMACHINE_CLEARS.MEMORY_ORDERING
d
Same Core Diff Cores Diff Socketssharing padded sharing padded sharing padded
CPI 1.3 0.7 1.4 0.4 1.7 0.4cycles 33130 17536 36012 9163 46484 9608instructions 26418 25865 26550 25747 26717 25768CLEARS 238 ≈0 ≈0 ≈0 ≈0 ≈0
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 58/65
Пример 3: разные ядра
L2_STORE_LOCK_RQSTS - L2 RFOs breakdown
Diff Cores Diff Socketssharing padded sharing padded
CPI 1.4 0.4 1.7 0.4LLC-stores 183 ≈0 49 ≈0LLC-store-misses 182 ≈0 48 ≈0L2_STORE_LOCK_RQSTS.MISS 134 ≈0 33 ≈0L2_STORE_LOCK_RQSTS.HIT_E ≈0 ≈0 ≈0 ≈0L2_STORE_LOCK_RQSTS.HIT_M ≈0 ≈0 ≈0 ≈0L2_STORE_LOCK_RQSTS.ALL 183 ≈0 49 ≈0
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 59/65
Внимание!Вопрос в зал!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 60/65
Пример 3: разные ядра
Diff Cores Diff Socketssharing padded sharing padded
CPI 1.4 0.4 1.7 0.4LLC-stores 183 ≈0 49 ≈0LLC-store-misses 182 ≈0 48 ≈0L2_STORE_LOCK_RQSTS.MISS 134 ≈0 33 ≈0L2_STORE_LOCK_RQSTS.ALL 183 ≈0 49 ≈0
Почему 183 > 49 и 134 > 33,а все равно работает быстрее?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 61/65
Пример 3: события считающие длительность
Есть и такое событие:OFFCORE_REQUESTS_OUTSTANDING.CYCLES_WITH_DEMAND_RFO
Diff Cores Diff Socketssharing padded sharing padded
CPI 1.4 0.4 1.7 0.4cycles 36012 9163 46484 9608instructions 26550 25747 26717 25768ORO.SWD_RFO 21723 10 29601 56
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 62/65
Заключение:
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 63/65
Заключение: Учиться, учиться и учиться!
Изучаем микроархитектуру:∙ “Computer Architecture: A Quantitative Approach”John L. Hennessy, David A. Patterson
∙ http://www.agner.org/optimize/
∙ http://www.google.com/search?q=Hardware+
performance+counter
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 64/65
Q & A ?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 65/65