Created
July 25, 2014 05:39
-
-
Save Rhomboid/1531c21c2c0391695966 to your computer and use it in GitHub Desktop.
Memory access - sequential vs. random
This file contains 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
#include <iostream> | |
#include <sstream> | |
#include <iomanip> | |
#include <vector> | |
#include <chrono> | |
#include <random> | |
#include <limits> | |
int main() | |
{ | |
std::mt19937 mt { 0xfeedbeef }; | |
std::vector<unsigned> testdata; | |
const size_t testsize = 1024 * 1024 * 25; | |
std::uniform_int_distribution<unsigned> datadist { 0, std::numeric_limits<unsigned>::max() }; | |
std::stringstream ss; | |
for(size_t i = 0; i < testsize; i++) { | |
testdata.push_back(datadist(mt)); | |
} | |
unsigned total = 0; | |
auto start = std::chrono::high_resolution_clock::now(); | |
for(auto val : testdata) { | |
total += val; | |
} | |
auto end = std::chrono::high_resolution_clock::now(); | |
ss << total; | |
std::cout << "sequential: " << std::right << std::setw(9) << std::fixed << std::setprecision(3) << (double)testsize * sizeof(unsigned) / 1024 / 1024 / | |
std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() * 1e9 << " MB/s\n"; | |
unsigned total2 = 0; | |
std::uniform_int_distribution<unsigned> indexdist { 0, testsize - 1 }; | |
auto start2 = std::chrono::high_resolution_clock::now(); | |
for(size_t i = 0; i < testsize; i++) { | |
total2 += testdata[indexdist(mt)]; | |
} | |
auto end2 = std::chrono::high_resolution_clock::now(); | |
ss << total2; | |
std::cout << "random: " << std::right << std::setw(9) << std::fixed << std::setprecision(3) << (double)testsize * sizeof(unsigned) / 1024 / 1024 / | |
std::chrono::duration_cast<std::chrono::nanoseconds>(end2 - start2).count() * 1e9 << " MB/s\n"; | |
} |
This file contains 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++ -Wall -Wextra -pedantic -std=c++1y -O3 -march=native memaccess.cpp -o memaccess && ./memaccess | |
sequential: 14283.674 MB/s | |
random: 164.464 MB/s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment