Python very slow on the Sharp Zaurus - any idea why?

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Jul 23 10:01:09 EDT 2002


Paul Rubin <phr-n2002b at NOSPAMnightsong.com> wrote in 
news:7xfzybii29.fsf at ruckus.brouhaha.com:

> Is the idea here to discover if a*b overflows 32 bits, if a and b are
> 32 bit ints?
> 
> On compilers supporting 64-bit (long long) ints, it may be faster to
> use them instead of floating point for this check.  I think that
> includes GCC and current Microsoft compilers among others.  

The Microsoft compiler certainly can do that. I think the code below does 
all the overflow checking, and the Microsoft compiler just uses the native 
multiply opcode to implement it:

#include <stdio.h>
#include <assert.h>

int safemultiply(__int32 a, __int32 b, __int32 *res)
{
    __int64 product = (__int64)a * b;
    __int32 low, hi;
    low = (__int32)(product & 0xFFFFFFFF);
    hi = (__int32)(product >> 32);
    if (hi == 0) {
        if (low < 0) return 0;
    } else if (hi == -1) {
        if (low >= 0) return 0;
    } else
        return 0;
    *res = low;
    return 1;
}

int main(int argc, char**argv)
{
    /* Some tests */
    __int32 res;
    assert(safemultiply(1, -2147483648, &res));
    assert(res == -2147483648);
    assert(!safemultiply(-1, -2147483648, &res));
    assert(!safemultiply(-2, -2147483648, &res));
    assert(!safemultiply(-2147483648, -2147483648, &res));
    assert(!safemultiply(-2, -2000000000, &res));
    assert(safemultiply(5, 5, &res));
    assert(res == 25);

    printf("All tests passed\n");
    return 0;
}


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list