Created
May 17, 2023 13:22
-
-
Save Const-me/4eb4f17932b561dd8fa2379beae2d370 to your computer and use it in GitHub Desktop.
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
#include <stdlib.h> | |
#include <vector> | |
#include <intrin.h> | |
#include <stdint.h> | |
#include <inttypes.h> | |
std::vector<char> makeTestVector( bool random ) | |
{ | |
std::vector<char> result; | |
result.resize( 1024 * 16 ); | |
if( random ) | |
{ | |
srand( 0 ); | |
for( char& ref : result ) | |
ref = ( rand() & 1 ) ? 1 : 0; | |
} | |
else | |
{ | |
for( size_t i = 0; i < result.size(); i++ ) | |
result[ i ] = ( i & 1 ) ? 1 : 0; | |
} | |
return result; | |
} | |
static size_t __declspec( noinline ) one() | |
{ | |
return 1; | |
} | |
size_t countWithBranches( const std::vector<char>& vec ) | |
{ | |
size_t res = 0; | |
const int64_t tsc = (int64_t)__rdtsc(); | |
_ReadBarrier(); | |
for( char c : vec ) | |
{ | |
if( c ) | |
res += one(); | |
} | |
const int64_t elapsed = (int64_t)__rdtsc() - tsc; | |
printf( "Elapsed time: %" PRIi64 "\n", elapsed ); | |
return res; | |
} | |
int main() | |
{ | |
// Flip this to true, re-compile, and retry | |
constexpr bool random = false; | |
const auto vec = makeTestVector( random ); | |
size_t res = countWithBranches( vec ); | |
printf( "Counter: %zu\n", res ); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment