Skip to content

Instantly share code, notes, and snippets.

@Const-me
Created May 17, 2023 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Const-me/4eb4f17932b561dd8fa2379beae2d370 to your computer and use it in GitHub Desktop.
Save Const-me/4eb4f17932b561dd8fa2379beae2d370 to your computer and use it in GitHub Desktop.
#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