-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
53 lines (42 loc) · 1.42 KB
/
Copy pathmain.cpp
File metadata and controls
53 lines (42 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <chrono>
#include <cstdint>
#include <iostream>
#include <numeric>
#include <vector>
struct Node {
Node* next;
};
double MeasureL1CacheLatency() {
// Standard L1 Data Cache is 32KB - 48KB.
// 1000 nodes of 64 bytes = 64KB (fits well within L1/L2 boundaries).
constexpr size_t NumNodes = 1024;
constexpr size_t Iterations = 100'000'000;
// Align nodes to cache line boundary to prevent split accesses
alignas(64) std::vector<Node> nodes(NumNodes);
// Set up pointer-chasing linked list (0 -> 1 -> 2 -> ... -> 0)
for (size_t i = 0; i < NumNodes - 1; ++i) {
nodes[i].next = &nodes[i + 1];
}
nodes[NumNodes - 1].next = &nodes[0];
// Warm up the L1 Cache by chasing pointers once
Node* current = &nodes[0];
for (size_t i = 0; i < NumNodes; ++i) {
current = current->next;
}
// Timed pointer-chasing loop
auto start = std::chrono::steady_clock::now();
for (size_t i = 0; i < Iterations; ++i) {
current = current->next;
}
auto end = std::chrono::steady_clock::now();
// Prevent compiler from optimizing away the loop
volatile auto sink = current;
(void)sink;
std::chrono::duration<double, std::nano> elapsed = end - start;
return elapsed.count() / Iterations;
}
int main() {
double latencyNs = MeasureL1CacheLatency();
std::cout << "L1 Cache Access Latency: " << latencyNs << " ns" << std::endl;
return 0;
}