Last active
November 17, 2021 06:10
-
-
Save frkd-dev/fa43d031740e6d63bb58e1120934e94e to your computer and use it in GitHub Desktop.
CPU cache lines and sizes test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g++ -std=c++11 -O2 -o cache_test cache_test.cpp | |
#include <iostream> | |
#include <time.h> | |
#include <sys/mman.h> | |
#define KB * 1024 | |
#define MB KB KB | |
const size_t memory_size = 32 MB; // memory size allocated for test | |
const size_t iterations = 1; // number of iterations for each test, increase by 10 if you get small timings | |
const size_t max_step = 1024; // max writing step to generate cache misses | |
// Get time in msec | |
uint64_t get_time() { | |
struct timespec tp; | |
clock_gettime(CLOCK_REALTIME, &tp); | |
return tp.tv_nsec / 1000000 + tp.tv_sec * 1000; | |
} | |
int main() { | |
using namespace std; | |
void* map = mmap(NULL, memory_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); | |
if (map == MAP_FAILED) | |
return 1; | |
uint32_t* data = (uint32_t*)map; | |
size_t count = memory_size / sizeof(uint32_t); | |
size_t total_writes = count * iterations; | |
// Warming up memory pages, so they truly allocated | |
for (size_t i = count - 1; i; i--) | |
data[i]++; | |
cout << " "; | |
for (size_t step = 1; step <= max_step; step *= 2) | |
printf("+%-7zu", step); | |
cout << '\n'; | |
// Go! | |
for (size_t chunk_size = 4 KB; chunk_size <= memory_size; chunk_size *= 2) { | |
printf("%8zu Kb : ", chunk_size / 1024); | |
const size_t step_mask = (chunk_size / sizeof(size_t)) - 1; | |
for (size_t step = 1; step <= max_step; step *= 2) { | |
uint64_t start = get_time(); | |
size_t i = total_writes; | |
size_t k = 0; | |
while (i) { | |
data[k] *= 3; | |
k += step; | |
k &= step_mask; | |
i--; | |
} | |
uint64_t end = get_time(); | |
printf("%-8llu", (end - start)); | |
} | |
cout << '\n'; | |
} | |
munmap(map, memory_size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment