Skip to content

Instantly share code, notes, and snippets.

@uvsmtid
Last active November 17, 2015 16:23
Show Gist options
  • Save uvsmtid/52caa3f2cfab287b2b80 to your computer and use it in GitHub Desktop.
Save uvsmtid/52caa3f2cfab287b2b80 to your computer and use it in GitHub Desktop.
// This is a C++ port from Java of Martin Thomson's code to demonstrate
// write combining buffers.
// See: http://mechanical-sympathy.blogspot.sg/2011/07/write-combining.html
#include <iostream>
#include <limits>
#include <chrono>
const int ITERATIONS = std::numeric_limits<int>::max();
const int ITEMS = 1 << 24;
const int MASK = ITEMS - 1;
char arrayA[ITEMS];
char arrayB[ITEMS];
char arrayC[ITEMS];
char arrayD[ITEMS];
char arrayE[ITEMS];
char arrayF[ITEMS];
std::chrono::duration<long, std::nano> runCaseOne()
{
auto start = std::chrono::high_resolution_clock::now();
int i = ITERATIONS;
while (--i != 0)
{
int slot = i & MASK;
char b = (char)i;
arrayA[slot] = b;
arrayB[slot] = b;
arrayC[slot] = b;
arrayD[slot] = b;
arrayE[slot] = b;
arrayF[slot] = b;
}
std::chrono::duration<long, std::nano> duration = std::chrono::high_resolution_clock::now() - start;
return duration;
}
std::chrono::duration<long, std::nano> runCaseTwo()
{
auto start = std::chrono::high_resolution_clock::now();
int i = ITERATIONS;
while (--i != 0)
{
int slot = i & MASK;
char b = (char)i;
arrayA[slot] = b;
arrayB[slot] = b;
arrayC[slot] = b;
}
i = ITERATIONS;
while (--i != 0)
{
int slot = i & MASK;
char b = (char)i;
arrayD[slot] = b;
arrayE[slot] = b;
arrayF[slot] = b;
}
std::chrono::duration<long, std::nano> duration = std::chrono::high_resolution_clock::now() - start;
return duration;
}
int main (int argc, char** argv)
{
for (int i = 1; i <= 3 ; i++) {
std::cout << i << " SingleLoop duration (ns) = " << runCaseOne().count() << std::endl;
std::cout << i << " SplitLoop duration (ns) = " << runCaseTwo().count() << std::endl;
}
int result = arrayA[1] + arrayB[2] + arrayC[3] +
arrayD[4] + arrayE[5] + arrayF[6];
std::cout << "result = " << result << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment