Re: [PATCH] ALSA: Remove subsystem-specific malloc (1/8)

From: Dave Jones
Date: Thu Jun 10 2004 - 07:35:00 EST


On Wed, Jun 09, 2004 at 10:08:34PM -0700, dean gaudet wrote:

> > +void *kcalloc(size_t n, size_t size, int flags)
> > +{
> > + if (n != 0 && size > INT_MAX / n)
> > + return NULL;
>
> division isn't very efficient :) it's typically a 40+ cycle operation.
>
> there's almost certainly more efficient ways to do this with per-target
> assembly... but you should probably just crib the code from glibc which
> avoids division for small allocations:
>
> /* size_t is unsigned so the behavior on overflow is defined. */
> bytes = n * elem_size;
> #define HALF_INTERNAL_SIZE_T \
> (((INTERNAL_SIZE_T) 1) << (8 * sizeof (INTERNAL_SIZE_T) / 2))
> if (__builtin_expect ((n | elem_size) >= HALF_INTERNAL_SIZE_T, 0)) {
> if (elem_size != 0 && bytes / elem_size != n) {
> MALLOC_FAILURE_ACTION;
> return 0;
> }
> }

Considering this isn't exactly a cycle-critical piece of code,
I'd choose readability over saving 40 cycles which is probably
lost in the noise of every other operation we do in that allocation.

Dave

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/