Skip to content

Instantly share code, notes, and snippets.

@acaly
Last active October 18, 2018 21:18
Show Gist options
  • Save acaly/9bcd62d6827ef7d5b503e07abb8480b9 to your computer and use it in GitHub Desktop.
Save acaly/9bcd62d6827ef7d5b503e07abb8480b9 to your computer and use it in GitHub Desktop.
Test speed of memory access across different pages
#include <cstdio>
#include <vector>
#include <chrono>
#include <thread>
static constexpr int test_size = 100000;
static constexpr int page_size = 4096;
static int data[test_size * page_size];
static int index[test_size];
static double run(bool warm_up, int n)
{
for (int i = 0; i < test_size; ++i)
{
index[i] = (i * page_size + (n % 100)) % (page_size * n);
}
if (warm_up)
{
for (int i = 0; i < test_size; ++i)
{
data[index[i]] = 1;
}
}
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < test_size; ++i)
{
data[index[i] + 1] = 2;
}
auto end = std::chrono::high_resolution_clock::now();
return (end - start).count() / 1000000.0;
}
static void flush_cache()
{
std::this_thread::yield();
for (int i = 0; i < test_size; ++i)
{
data[i * page_size] = 0;
}
}
int main(int argc, const char* argv[])
{
std::vector<int> s;
for (int i = 1; i < test_size; i *= 2)
{
s.push_back(i);
}
s.push_back(test_size);
std::printf("Warm up.\n");
for (std::size_t i = 0; i < s.size(); ++i)
{
std::printf("%d:\t%f\n", s[i], run(true, s[i]));
flush_cache();
}
std::printf("\nNo warm up.\n");
for (std::size_t i = 0; i < s.size(); ++i)
{
std::printf("%d:\t%f\n", s[i], run(false, s[i]));
flush_cache();
}
std::getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment