I’m using gcc 4.6.3 and creating a large array of random shorts. I’m generating them with the following statements:
val = SHRT_MAX; //as defined by limits.h
while(array<end) {
*array++ = rand() % val;
}
This is a considerably fast operation, and even for arrays as large as 5,000,000 elements is completed almost instantly. I was curious about my sorts efficiency with a smaller variation in numbers and changed that to:
val = 3;
This caused a considerable speed difference, it ran much slower than the original statements. What is it that is causing such a considerable speed difference?
SHRT_MAXis most likely greater than or equal toRAND_MAX. The statement:can be optimized into:
which is faster because it replaces a modulus with a branch. The second version, where
valis 3, cannot be optimized into a simpler version that runs without modulus.% SHRT_MAXcannot be simplified into a bitwise operation. But combined with knowledge of howrand()is specified, the compiler can certainly optimize statements dealing withrand()and values greater than or equal toRAND_MAX.