Summary - Performance
- C++ course
- Expert
- Lesson 30/47
- 5 min
Combine profiling, cache and move semantics to write an optimized copy function.
Summary - Performance
In this group you saw the performance tools: profiling, cache, vectorization, inline and move. All speed up the program; but only measurement gives correct use.
Now you will combine them in an inline + vectorizable loop example. You will combine inline int doubled(int x) with a cache-friendly loop; this shows how the performance tools work together.
Inline + vectorizable loop
Calling an inline function inside a loop lets the compiler do both inlining and vectorization. Example: inline int doubled(int x) { return x * 2; } called in a loop lets the compiler spread the body into the loop and process with SIMD.
Example: int a[3] = {1, 2, 3}; int s = 0; for (int i = 0; i < 3; ++i) s += a[i]; std::cout << s + doubled(5);. Here s=6, doubled(5)=10, total 16. This small example shows how inline and loops combine.
Practice Combine inline + loop
Write inline int doubled(int x) with body return x * 2;. In main define int a[3] = {1, 2, 3};, int s = 0;; write for (int i = 0; i < 3; ++i) s += a[i];; then write std::cout << s + doubled(5);.
Starter code
#include <iostream>
// Define the inline doubled function here
int main() {
// Sum the a array, combine with doubled(5) and print
return 0;
}Sample solution
#include <iostream>
inline int doubled(int x) {
return x * 2;
}
int main() {
int a[3] = {1, 2, 3};
int s = 0;
for (int i = 0; i < 3; ++i) s += a[i];
std::cout << s + doubled(5);
return 0;
}Expected output
16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which access pattern is cache-friendly?
for (int i = 0; i < n; ++i) sum += data[i];- Random-index access
- Sequential-index access Correct answer
- Only even-index access
- Strided access
Explanation: Sequential access gives spatial locality.
2 Complete the inline function
inline int doubled(int x) { return x * ____; }
inline int doubled(int x) { return x * 2; }
Explanation: Write return x * 2;; doubled computes the double.
3 Match each tool to its trait
| Term | Meaning |
|---|---|
profiling |
Bottleneck measure |
cache |
Speed via locality |
vectorization |
SIMD parallelism |
move |
Resource transfer |