Last active
May 18, 2021 03:12
-
-
Save zhuyie/1b7784d7fd457ada1ff45d3ce4771080 to your computer and use it in GitHub Desktop.
test-branch-prediction
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 <cstdio> | |
#include <cstdlib> | |
#include <vector> | |
#include <random> | |
#include <algorithm> | |
#include <chrono> | |
using namespace std::chrono; | |
static int dummy[2]; | |
int main(int argc, char* argv[]) | |
{ | |
// parsing command line | |
bool sort = false; | |
if (argc > 1 && strcmp(argv[1], "1") == 0) { | |
sort = true; | |
} | |
// prepare test data (uniformly distributed random values) | |
const int arraySize = 5000; | |
std::vector<int> data; | |
data.resize(arraySize); | |
std::random_device rd; | |
std::mt19937 gen(rd()); | |
std::uniform_int_distribution<> dis(0, 256); | |
for (int i = 0; i < arraySize; i++) { | |
data[i] = dis(gen); | |
} | |
// sort or not | |
if (sort) { | |
std::sort(data.begin(), data.end()); | |
} | |
auto start = system_clock::now(); | |
unsigned int count[2]; | |
const int testN = 100000; | |
for (int t = 0; t < testN; ++t) { | |
// main loop | |
memset(count, 0, sizeof(count)); | |
for (int i = 0; i < arraySize; ++i) { | |
if (data[i] < 128) { | |
dummy[0] *= dummy[1]; // consume-a-few-cycles | |
count[0]++; // counting | |
} else { | |
dummy[1] *= dummy[0]; // consume-a-few-cycles | |
count[1]++; // counting | |
} | |
} | |
} | |
auto duration = duration_cast<microseconds>(system_clock::now() - start); | |
fprintf(stdout, "sort = %d\n", sort ? true : false); | |
fprintf(stdout, "total = %d\n", arraySize); | |
fprintf(stdout, "count = [%u,%u]\n", count[0], count[1]); | |
fprintf(stdout, "duration = %.2fms\n", duration.count()/1000.0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On my MacBook Pro (16-inch, 2019):
➜ build ./test-branch-prediction 0
sort = 0
total = 5000
count = [2416,2584]
duration = 1245.34ms
➜ build ./test-branch-prediction 1
sort = 1
total = 5000
count = [2480,2520]
duration = 770.38ms