Нередко при анализе производительности приложений приходится много копать. Но просто копать недостаточно, нужно еще разгребать накопанное. Железный век настал более 3000 лет назад, и было бы удивительно, если бы за это время человечество не создало кучу разнообразных железных приспособлений для копания и разгребания.
Данный доклад рассказывает, что же такое «Hardware Performance Counters», где их найти и как их можно использовать для анализа производительности.
2. The following is intended to outline our general product direction. It
is intended for information purposes only, and may not be
incorporated into any contract. It is not a commitment to deliver any
material, code, or functionality, and should not be relied upon in
making purchasing decisions. The development, release, and timing
of any features or functionality described for Oracle’s products
remains at the sole discretion of Oracle.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 2/65
3. Глава первая
Очень краткое введение в
Методологию Оптимизации
Производительности,
«Что-Где-Как» и «Сверху-Вниз»,
а также о роли «железных» счетчиков
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 3/65
5. 3 магических вопроса
Что?
∙ Что мешает работать быстрее? (monitoring)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
6. 3 магических вопроса
Что? ⇒ Где?
∙ Что мешает работать быстрее? (monitoring)
∙ Где это находится? (profiling)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
7. 3 магических вопроса
Что? ⇒ Где? ⇒ Как?
∙ Что мешает работать быстрее? (monitoring)
∙ Где это находится? (profiling)
∙ Как это исправить? (tuning/optimizing)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 4/65
8. Сверху-Вниз
∙ Системный уровень
– 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
13. Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .
⇓
∙ Много %irq, %soft ⇒ . . .
⇓
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
14. Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .
⇓
∙ Много %irq, %soft ⇒ . . .
⇓
∙ Много %iowait ⇒ . . .
⇓
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
15. Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .
⇓
∙ Много %irq, %soft ⇒ . . .
⇓
∙ Много %iowait ⇒ . . .
⇓
∙ Много %idle ⇒ . . .
⇓
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
16. Сверху-Вниз
Мониторим (e.g. mpstat)
∙ Много %sys ⇒ . . .
⇓
∙ Много %irq, %soft ⇒ . . .
⇓
∙ Много %iowait ⇒ . . .
⇓
∙ Много %idle ⇒ . . .
⇓
∙ Много %user
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 8/65
17. Глава вторая
О высоком.
О высокой загрузке процессора,
а также
главный вопрос жизни и всего остального
«Кто виноват?»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 9/65
18. CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
19. CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?
– Как часто OS ставит процессы на исполнение.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
20. CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?
– Как часто OS ставит процессы на исполнение.
Профилирование?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
21. CPU Utilization
∙ О чём говорит ∼100% CPU Utilization?
– Как часто OS ставит процессы на исполнение.
Профилирование?
Профилирование покажет
«ГДЕ» программа проводит время,
без ответа на вопрос «ПОЧЕМУ».
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 10/65
23. Кто виноват?
Сложная микроархитектура современных CPU:
e.g.
Sergey Kuksenko
«Quantum Performance Effects»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 11/65
24. Кто виноват?
Сложная микроархитектура современных 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
26. PMU: Performance Monitoring Unit
Performance Monitoring Unit - это встроенный хардверный
профайлер внутри процессора.
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 14/65
27. 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
28. События
Читаем документацию от производителя! (e.g. 2 страницы из 32)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 15/65
29. События
Проблемы:
∙ Тысяча их!
∙ Требуют знания микроархитектуры
∙ Платформозависимые
– сильно различаются у разных производителей CPU
– могут сильно меняться у одного производителя при смене
микроархитектуры
∙ Как с ними вообще работать?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 16/65
30. 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
31. 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
32. 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
33. HWC: использование
∙ валидация железа
∙ анализ производительности
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 20/65
34. 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
35. 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
36. HWC: tools(cont.)
∙ AMD CodeXL
∙ Intel Vtune Amplifier XE
∙ etc...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 22/65
38. События 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
39. Глава четвертая
Я собрал данные HWC, и?
или
Введение в микроархитектурный
анализ производительности
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 25/65
40. Время работы
𝑡𝑖𝑚𝑒 = 𝑐𝑦𝑐𝑙𝑒𝑠
𝑓 𝑟𝑒𝑞𝑢𝑒𝑛𝑐𝑦
Оптимизация это
уменьшение количества тактов (cycles)!
⋆
⋆
все остальное - overclocking
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 26/65
41. ГУМ
Главное Уравнение Микроархитектуры:
𝑐𝑦𝑐𝑙𝑒𝑠 = 𝑃 𝑎𝑡ℎ𝐿𝑒𝑛𝑔𝑡ℎ * 𝐶𝑃 𝐼 = 𝑃 𝑎𝑡ℎ𝐿𝑒𝑛𝑔𝑡ℎ * 1
𝐼𝑃 𝐶
∙ PathLength - количество инструкций
∙ CPI - cycles per instruction
∙ IPC - instructions per cycle
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 27/65
42. 𝑃 𝑎𝑡ℎ𝐿𝑒𝑛𝑔𝑡ℎ * 𝐶𝑃 𝐼
∙ PathLength - мера эффективности алгоритма
(чем меньше, тем лучше)
∙ CPI - мера эффективности работы CPU
(чем меньше, тем лучше)
– 𝐶𝑃 𝐼 = 4 – плохо!
– 𝐶𝑃 𝐼 = 1
∙ Nehalem – сойдет!
∙ SandyBridge и позже – плоховатенько!
– 𝐶𝑃 𝐼 = 0.4 – хорошо!
– 𝐶𝑃 𝐼 = 0.2 – идеально!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 28/65
43. Что делать?
∙ низкий 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
44. Проблемы с CPI?
Нам нужна классификация проблем!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 30/65
45. 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
46. 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
47. 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
49. Пример первый
Некий «большой» индустриальный
Java бенчмарк
Который до сих пор снится по ночам многим
Java Performance инженерам
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 35/65
50. Пример 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
51. Пример 1: обработанный руками perf stat -d
IPC 0.54
cycles ×1012
2.28
instructions ×1012
1.23
L1-dcache-loads ×109
338
L1-dcache-load-misses ×109
38
LLC-loads ×109
25
dTLB-loads ×109
337
dTLB-load-misses ×109
6
iTLB-loads ×109
12
iTLB-loads-misses ×106
432
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
52. Пример 1: обработанный руками perf stat -d
IPC 0.54
cycles ×1012
2.28
instructions ×1012
1.23
L1-dcache-loads ×109
338
L1-dcache-load-misses ×109
38
LLC-loads ×109
25
dTLB-loads ×109
337
dTLB-load-misses ×109
6
iTLB-loads ×109
12
iTLB-loads-misses ×106
432
Проблемы?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
55. Пример 1: обработанный руками perf stat -d
IPC 0.54
cycles ×1012
2.28
instructions ×1012
1.23
L1-dcache-loads ×109
338
L1-dcache-load-misses ×109
38
LLC-loads ×109
25
dTLB-loads ×109
337
dTLB-load-misses ×109
6
iTLB-loads ×109
12
iTLB-loads-misses ×106
432
Проблемы!
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 37/65
56. Пример 1: dTLB misses
TLB = Translation Lookaside Buffer
∙ Кэш транслятора виртуальных адресов в физические
∙ Каждое обращение к памяти – обращение к TLB
∙ TLB miss может стоить сотни тактов
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 38/65
57. Пример 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
62. Пример второй
Мы нашли горячий метод
или
О
⋆
применимости алгоритмических оптимизаций
⋆
О-обычное
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 42/65
63. Пример 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. 43/65
64. Пример 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
65. Пример 2: "Ok Google"
𝑂( 𝑁2.81)
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 44/65
66. Пример 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 sec Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 45/65
67. А если мы пойдем другим путем?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 46/65
68. Пример 2: JMH, -prof perfnorm, N=256
per multiplication per iteration
CPI 1.06
cycles 146 × 106
8.7
instructions 137 × 106
8.2
L1-loads 68 × 106
4
L1-load-misses 33 × 106
2
L1-stores 0.56 × 106
L1-store-misses 38357
LLC-loads 26 × 106
1.6
LLC-stores 11595
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 47/65
69. Пример 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
70. Пример 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
71. Пример 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
75. Пример 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
...
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 52/65
76. Пример 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
77. Пример третий
«++ на оба ваши треда»
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 53/65
78. Пример 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
79. Пример 3: измерим
что общего sharing padded
Same Core (HT) L1 9.5 4.9
Diff Cores (within socket) L3 (LLC) 10.6 2.8
Diff Sockets ничего 18.2 2.8
average time, ns/op
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 55/65
81. Пример 3: соберем HWC (продолжение)
Данные нормализованы на 103
операций
Same Core Diff Cores Diff Sockets
sharing padded sharing padded sharing padded
LLС-loads 4 3 58 1 32 1
LLC-load-misses 1 1 53 ≈0 35 ≈0
LLC-stores 1 1 183 ≈0 49 ≈0
LLC-store-misses 1 ≈0 182 ≈0 48 ≈0
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 57/65
82. Пример 3: На честном слове и на одном ядре
для одного ядра нам нужно считать
MACHINE_CLEARS.MEMORY_ORDERING
Same Core Diff Cores Diff Sockets
sharing padded sharing padded sharing padded
CPI 1.3 0.7 1.4 0.4 1.7 0.4
cycles 33130 17536 36012 9163 46484 9608
instructions 26418 25865 26550 25747 26717 25768
CLEARS 238 ≈0 ≈0 ≈0 ≈0 ≈0
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 58/65
88. Заключение: Учиться, учиться и учиться!
Изучаем микроархитектуру:
∙ “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
89. Q & A ?
Copyright c○ 2015, Oracle and/or its affiliates. All rights reserved. 65/65