R
REH
REH said:Well, efficiency is relative, [...]
Well if you are willing to perform divisions, then indeed it most
certainly is!
My point was under many circumstances, that won't matter. People spend way
to much time worrying about speed before it is even an issue. If, for
example, a real-time system can meet all of its scheduled dead-lines with
the required amount of reserved processor time, then what does it matter if
it takes twice as long as it could without the checks? Or, take a
command-line tool executed from the shell. Whether it takes 1ms or 100ms,
it is still "instantaneous" to the user.
Yes, reread what I wrote above.[...] but I am currently only concerned with it
being correct and standard compliant. For unsigned multiplication, I am
currently do something like (ignoring 0 for the example):
a = b * c;
if (c != a / b)
overflow();
That's fine except for when b is zero.
I prefer simpler, easy to read code. I worry about speed when its an issue.How about:
if (0 != b && a/b != c) overflow ();
If you want to skip the cost of the division in many cases, then:
#define HALF_WAY (1 << (sizeof (unsigned)+1)/2)
if ((b|c) >= HALF_WAY &&
((b >= HALF_WAY && c >= HALF_WAY) || (0 != b && a/b != c)))
overflow ();
And of course you can go further by simulating the multiply as 4
smaller multiplies and then checking the high multiply then the sum of
the other 3 for overflow.
All this for what can be done in basically 1 to 3 more instructions in
most assembly languages.
I don't plan to use this code in generating an FFT. For such code, with a
lot going on in tight loops, it would probably matter. In many other types
of code, I doubt you would notice any difference.
REH