Master the fundamental concepts of cache optimization through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksWhen each thread increments its own counter in a shared array, placing counters 8 bytes apart packs eight of them into one 64-byte line. Padding or aligning each counter to 64 bytes gives each thread a private line.
Use alignas(64) on struct fields or insert explicit char padding arrays. Verify sizeof and offsets with offsetof before trusting layout.
cLoading…
std::hardware_destructive_interference_size documents line size when availableperf c2c validationKeep the relevant documentation open while you implement. When your output disagrees with the reference, trace one failing case by hand before changing random lines.
You will pad a struct array so threads no longer false-share, then benchmark before and after. This exercise requires measuring contention drops, not just showing the layout change.
Field order changes the size of a C struct: every member is aligned to its own alignment, so a char before a double wastes 7 bytes. Alignment also decides which cache line each array element lands in, and elements sharing a line is exactly how per-thread counters end up false sharing. Write a struct-layout calculator for the x86-64 System V ABI. It prints offsets and padding, reorders fields to remove padding, applies __attribute__((aligned(N))), and maps an array of structs onto cache lines.
cLoading…
Types (size/alignment): char bool uint8_t 1, short uint16_t 2, int float uint32_t 4, long double pointer uint64_t size_t 8, long_double 16. A struct used as a field has its computed size and alignment.
NAME_reordered, with the fields stably sorted by alignment from largest to smallest, and reports the bytes saved. The original is not changed.S: unknown type T (the field is skipped), unknown struct S, aligned: N is not a power of two, array: invalid count or line size, and array: struct S is empty.cLoading…
Offsets are right-aligned in 4 columns. The padding percentage is rounded half up to 1 decimal using integer arithmetic. Only padding at the struct's own level is counted, not padding inside nested structs.
Input:
cLoading…
Output:
cLoading…
offsetof/sizeof if you like. Never hard-code sizes.Hidden tests cover arrays of odd-sized structs that straddle lines, nested structs, long_double, a struct that is already optimal (reordering saves 0 bytes), forcing 64-byte alignment to give each element its own line, and every error message.