Profile C Execution

So, just for fun and out of curiosity, I wanted to see what happens faster when an even check, module or bitwise comparisons are performed.

So, I hacked the following, but I'm not sure if it behaves correctly, since the difference is so small. I read somewhere that a bit number should be an order of magnitude faster than a module check.

Is it possible that it will be optimized? I just started building, otherwise I’ll try to analyze the executable file a bit.

EDIT 3: Here is a working test, thanks to the @phonetagger great way:

#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 ));
}

5 billion iterations of each loop with global compiler optimization removes the following:

Mod: 93.099101
Bit: 16.701401
Dif: 76.397700
+5
source share
3 answers

():

if( ( i % 2 ) == 0 )

if( ( i & 1 ) == 0 )

... "" . , MOD IN-IN , % 2, , & 1. , MOD -2 . , , , , , ' -, , ; .. GLOBALLY-DECLARED (.. "" ) , , . main() , , , , , .

, .... - ( → ). (< <), ( ) . , , 15 - 80 , → . " ", , , .

EDIT: (, , Sparc v8), . , . .

+2

gcc foo.c -std=c99 -S -O0 (, -O0) x86 . , if andl, ( , Intel):

:

.L6:
        movl    72(%esp), %eax
        andl    $1, %eax
        testl   %eax, %eax
        jne     .L5
        call    doNothing
.L5:
        addl    $1, 72(%esp)
.L4:
        movl    LOOPS, %eax
        cmpl    %eax, 72(%esp)
        jl      .L6

:

.L9:
        movl    76(%esp), %eax
        andl    $1, %eax
        testl   %eax, %eax
        jne     .L8
        call    doNothing
.L8:
        addl    $1, 76(%esp)
.L7:
        movl    LOOPS, %eax
        cmpl    %eax, 76(%esp)
        jl      .L9

, , , / clock.

+3

( "..., 0x01" ); .

Modulo , , , ( !). - ; , , "modulo (x, 2)" AND.

PARLANSE , . , C ++ .

"" , / ( " " ) ; .

+2

All Articles