Summary - Performance
- C course
- Advanced
- Lesson 78/83
- 5 min
Combine profiling, cache and loop optimization to write a copy function.
Summary - Performance
In this group you learned profiling, cache effects, loop optimization, inline and memory alignment. Now you'll combine them into an aligned and unrolled copy function.
The copy_block function copies an int array with 4-way unroll; each iteration copies 4 elements. It copies the {1,2,3,4} array to a destination and prints the destination. All output is deterministic: kopya 1 2 3 4.
Practice copy_block function
Write void copy_block(const int *src, int *dst, int n): int i;, 4-way unroll for (i = 0; i + 3 < n; i += 4) { dst[i] = src[i]; dst[i+1] = src[i+1]; dst[i+2] = src[i+2]; dst[i+3] = src[i+3]; }, remainder for (; i < n; i++) dst[i] = src[i];. In main declare int src[] = {1,2,3,4};, int dst[4] = {0};, call copy_block(src, dst, 4); and print printf("kopya: %d %d %d %d\n", dst[0], dst[1], dst[2], dst[3]);.
Starter code
#include <stdio.h>
// Write copy_block: 4-way unroll + remainder loop
// main: copy 4-element src into dst and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
void copy_block(const int *src, int *dst, int n) {
int i;
for (i = 0; i + 3 < n; i += 4) {
dst[i] = src[i];
dst[i+1] = src[i+1];
dst[i+2] = src[i+2];
dst[i+3] = src[i+3];
}
for (; i < n; i++) dst[i] = src[i];
}
int main(void) {
int src[] = {1,2,3,4};
int dst[4] = {0};
copy_block(src, dst, 4);
printf("kopya: %d %d %d %d\n", dst[0], dst[1], dst[2], dst[3]);
return 0;
}Expected output
kopya: 1 2 3 4
Next steps
You learned the performance basics: profiling, cache, loop unrolling, inline and alignment. These are core tools of systems programming.
Next steps: CPU counters with perf stat, 8- or 16-element parallel processing with SIMD vector instructions, branch prediction with __builtin_expect, and multi-node memory management with numa. The patterns you learned are the foundation of these advanced techniques.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does copy_block get faster?
- Column-major
- 4-way unroll Correct answer
- Slow loop
- Random access
Explanation: 4-way unroll copies 4 elements per iteration; overhead drops.
2 Match performance tools
| Term | Meaning |
|---|---|
clock |
Measures time |
row-major |
Cache friendly |
unroll |
Cuts loop overhead |
_Alignof |
Gives alignment |