This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: question regarding div / std::div implementation


On Wed, Apr 20, 2016 at 6:38 PM, Paul Eggert <eggert@cs.ucla.edu> wrote:
> On 04/20/2016 02:15 PM, Daniel Gutson wrote:
>>
>> OK with no inline asm, but a libcall might be expensive specially in a
>> tight loop and messes with predictions;
>> a builtin is nonportable as well.
>
>
> In practice, C programs that need integer quotient and remainder typically
> don't call 'div'. They just use % and /, and compilers are now smart enough
> to do just one machine-level operation to get both quotient and remainder.
> For example, time/offtime.c has this macro:
>
> #define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
>
> which should work just fine as-is. In theory one could change this to use
> div/ldiv/lldiv, but why bother making the code way more complicated?

I personally see the macro above more complicated to read that a
simple function call with a meaningful name.

Additionally, consider

int foo(int x, int y)
{
    if (x > 0 && y > 0)
        return x * y * foo(x - 1, y - 1);
    else
        return 1;
}

int addqr2(int x, int y)
{
    const int quot = x / y;
    int something = x + y - 2 * x * y;
    int something_else = something * foo(x + 1, y + 1);
    const int rem = x % y;
    return quot + rem + something_else;
}

That fools the compiler. Moving the % just below the / induces the
optimization; but we'd be relying on a weak pattern recognition. Code
should not rely on that IMHO.
Anyway I already filed the issue to the gcc bugzilla, and if people
agrees there, I will ask them to assign it to someone of my team.

>
> As the 'div' function family was designed back when C compilers were not
> that smart and is largely obsolete now, simplicity would appear to be more
> important than performance here. Perhaps someone someday will work up the
> energy to get 'div' removed from the C standard.



-- 

Daniel F. Gutson
Engineering Manager

San Lorenzo 47, 3rd Floor, Office 5
CÃrdoba, Argentina

Phone:   +54 351 4217888 / +54 351 4218211
Skype:    dgutson
LinkedIn: http://ar.linkedin.com/in/danielgutson


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]