in reply to Re: Testing a number for oddness
in thread Testing a number for oddness
To get gcc to not optimize anything away do something like this:
NOTES: x is initialized with a non-zero value. On x86 I have noticed sometimes ALU/Mult operations on zero-valued inputs can be significantly faster than on non-zero inputs.#include <stdio.h> volatile int yb; int foo; void blah(int t) { foo = (t==0)? 1: 2; } int main(int argc, char **argv) { int x = 0xdeadbeef; volatile int *y = &yb; int i; int t = atoi(argv[1]); blah(t); if (t == 0) { printf("Using the & method\n"); for (i=0;i<100000000;++i) *y=x & foo; } else { printf("Using the %% method\n"); for (i=0;i<100000000;++i) *y=x % foo; } return 0; }
y is a volatile pointer to prevent gcc from optimizing the loops away, if it was so inclined.
'foo' is not a constant to prevent gcc from optimizing an odd/even test.
'foo' is initialized in a non-static function to prevent gcc from (if it could/would do this) optimizing the loops to odd/even test anyway.
We do 100 million iterations, to drown out any noise.
Running on an unloaded 933Mhz P-III:
% time ./foo 0 Using the & method 0.77user 0.01system 0:00.80elapsed 96%CPU (blah blah) % time ./foo 1 Using the % method 4.29user 0.00system 0:04.43elapsed 96%CPU (blah blah)
I ran the tests about 10 times each and the results are about the same.
Now if you are just doing a odd-even test, gcc will likely be able to optimize it for you to the point that you can use whatever method you want and it will be fast. If you programming on a DSP, however, or maybe in a super-high-speed driver or something, you'd want to make sure you use the fast version, cuz the compiler in that case likely can't help you (or you don't want it to).
And in Perl anyway, you are operating many levels about the underlying machine architecture. % vs & is the least of your worries speed-wise.
|
|---|