ですから、楽しみのために、そして好奇心から、偶数のチェック、モジュラス、またはビット単位の比較を行うと、何がより速く実行されるかを確認したかったのです。
そこで、以下をまとめましたが、違いが小さいので、正しく動作しているかわかりません。私はオンラインのどこかで、ビット単位の方がモジュラスチェックよりも桁違いに速いはずだと読みました。
最適化されている可能性はありますか?アセンブリをいじり始めたばかりです。さもなければ、実行可能ファイルを少し分析しようとします。
編集3:これが動作テストです。@phonetaggerに大いに感謝します。
#include <stdio.h>
#include <time.h>
#include <stdint.h>
// to reset the global
static const int SEED = 0x2A;
// 5B iterations, each
static const int64_t LOOPS = 5000000000;
int64_t globalVar;
// gotta call something
int64_t doSomething( int64_t input )
{
return 1 + input;
}
int main(int argc, char *argv[])
{
globalVar = SEED;
// mod
clock_t startMod = clock();
for( int64_t i=0; i<LOOPS; ++i )
{
if( ( i % globalVar ) == 0 )
{
globalVar = doSomething(globalVar);
}
}
clock_t endMod = clock();
double modTime = (double)(endMod - startMod) / CLOCKS_PER_SEC;
globalVar = SEED;
// bit
clock_t startBit = clock();
for( int64_t j=0; j<LOOPS; ++j )
{
if( ( j & globalVar ) == 0 )
{
globalVar = doSomething(globalVar);
}
}
clock_t endBit = clock();
double bitTime = (double)(endBit - startBit) / CLOCKS_PER_SEC;
printf("Mod: %lf\n", modTime);
printf("Bit: %lf\n", bitTime);
printf("Dif: %lf\n", ( modTime > bitTime ? modTime-bitTime : bitTime-modTime ));
}
コンパイラーの最適化をグローバルに削除して、各ループを50億回繰り返すと、次のようになります。
Mod: 93.099101
Bit: 16.701401
Dif: 76.397700