Code efficiency

sinck@corp.quepasa.com sinck@corp.quepasa.com
Mon, 7 Feb 2000 14:04:40 -0700


I was chatting with my carpool buddy on the way home (suprise), and he
stated that coding something along the lines of

    while (--i > 0)
      {
	  p++;
      }

would be faster than a classic

    for (i = 0; i < 50; i++)
      {
	  p++;
      }

based on the predecrement already setting the zero flags in the
appropriate registers and involving fewer instructions.

Well, I thought to myself, self, "I don't believe that it would make a
bit of difference using modern compilers."  Furthermore, myself went
on: "I bet gcc -O2 and stripping make more difference in the size."  So
I set out with the following .c file:


---------opt.c----------
#ifdef normal
main ()
{
    int i,p;
    p = 0;
    for (i = 0; i < 50; i++)
      {
	  p++;
      }
}
#endif



#ifdef mikeopt
main ()
{
    int i,p;

    i = 51;
    p = 0;

    while (--i > 0)
      {
	  p++;
      }
}
#endif


#ifdef sinckopt
main ()
{
    int i,p;
    p = 0;

    for (i=-1; ++i < 50;)
      {
	  p++;
      }
}
#endif
--------end opt.c----------

Not the prettiest of C, but it works and gives the same number of
loops.

So, I built the said files (without -O2) and stripped them and came up with:

-rwxr-xr-x   1 sinck    sinck       11624 Feb  6 11:49 loop-mikeopt*
-rwxr-xr-x   1 sinck    sinck        2976 Feb  6 11:49 loop-mikeopt-stripped*
-rwxr-xr-x   1 sinck    sinck       11624 Feb  6 11:49 loop-normal*
-rwxr-xr-x   1 sinck    sinck        2976 Feb  6 11:49 loop-normal-stripped*
-rwxr-xr-x   1 sinck    sinck       11624 Feb  6 11:49 loop-sinckopt*
-rwxr-xr-x   1 sinck    sinck        2976 Feb  6 11:49 loop-sinckopt-stripped*

All the non-stripped are the same; all the stripped are the same.

Now, with -O2 enabled:

-rwxr-xr-x   1 sinck    sinck       11592 Feb  6 11:50 loop-mikeopt*
-rwxr-xr-x   1 sinck    sinck        2944 Feb  6 11:50 loop-mikeopt-stripped*
-rwxr-xr-x   1 sinck    sinck       11592 Feb  6 11:50 loop-normal*
-rwxr-xr-x   1 sinck    sinck        2944 Feb  6 11:50 loop-normal-stripped*
-rwxr-xr-x   1 sinck    sinck       11592 Feb  6 11:50 loop-sinckopt*
-rwxr-xr-x   1 sinck    sinck        2944 Feb  6 11:50 loop-sinckopt-stripped*

Smaller than previous, but still grouped the same.

So, by decreasing filesizes:
non-optimized non-stripped
    optimized non-stripped
non-optimized stripped
    optimized stripped

And yes, it did make a bit of difference.  Somewhere in the binary
files produced, something is not the same.  :-)

My moral would be thus: code for supportability and leave the magic to
the compiler.

And yes, I know I didn't benchmark them running, but I didn't really
feel like trying to control the free parameters enough to get an
accurate benchmarking. 

This potentially uninformative tale brought to you by the letter C,
the number 50, and special guest Mike.

David