dimanche 28 juin 2015

Why is modulus with unsigned int runs faster than with unsigned long long?

Why to test speed of modulus?


I have an app where modulus operation is performed millions times a second. I have to work with very big numbers, so I chose unsigned long long as a data type. About a week ago I've written a new algorithm for my app that required performing modulus operation on numbers which are much less than the numbers I used to work with (e.g. 26 instead of 10000000). I chose to use unsigned int as a data type. The speed increased dramatically while the algorithm is almost the same.

Testing...


I've written two simple programs in C to test the speed of modulus calculation.

#include <stdio.h>

typedef unsigned long long ull;

int main(){
   puts("Testing modulus...");
   ull cnt;
   ull k;
   for(k=1, cnt=98765432;k<=10000000;++k) 
      printf("%u ",cnt%80);
   puts("");
   return 0;
}

The only thing I was changing was the type of the variable called cnt. I added the printf call to be sure that nothing gets optimized away.

I tested these programs with time ./progname > /dev/null and the results were as follows.

  • With unsigned long long: 14.5 sec
  • With unsigned int: 11.2 sec

Note: I'm testing it on a jailbroken iPad, that's why it takes so much time.

Why?


Why does the version with unsigned long long take so much time to run?

Aucun commentaire:

Enregistrer un commentaire