Author: hailfinger Date: 2009-11-25 17:58:17 +0100 (Wed, 25 Nov 2009) New Revision: 780
Modified: trunk/bitbang_spi.c trunk/ft2232_spi.c Log: Reduce realloc syscall overhead for FT2232 and bitbang.
FT2232 ran realloc() for every executed command. Start with a big enough buffer and don't touch buffer size unless it needs to grow. Bitbang was slightly better: It only ran realloc() if buffer size changed. Still, the solution above improves performance and reliability.
Signed-off-by: Carl-Daniel Hailfinger c-d.hailfinger.devel.2006@gmx.net Acked-by: Sean Nelson audiohacked@gmail.com
Modified: trunk/bitbang_spi.c =================================================================== --- trunk/bitbang_spi.c 2009-11-25 16:41:50 UTC (rev 779) +++ trunk/bitbang_spi.c 2009-11-25 16:58:17 UTC (rev 780) @@ -87,14 +87,16 @@ static unsigned char *bufout = NULL; static unsigned char *bufin = NULL; static int oldbufsize = 0; - int bufsize = max(writecnt + readcnt, 260); + int bufsize; int i;
/* Arbitrary size limitation here. We're only constrained by memory. */ if (writecnt > 65536 || readcnt > 65536) return SPI_INVALID_LENGTH;
- if (bufsize != oldbufsize) { + bufsize = max(writecnt + readcnt, 260); + /* Never shrink. realloc() calls are expensive. */ + if (bufsize > oldbufsize) { bufout = realloc(bufout, bufsize); if (!bufout) { fprintf(stderr, "Out of memory!\n"); @@ -109,6 +111,7 @@ free(bufout); exit(1); } + oldbufsize = bufsize; } memcpy(bufout, writearr, writecnt);
Modified: trunk/ft2232_spi.c =================================================================== --- trunk/ft2232_spi.c 2009-11-25 16:41:50 UTC (rev 779) +++ trunk/ft2232_spi.c 2009-11-25 16:58:17 UTC (rev 780) @@ -200,14 +200,22 @@ static unsigned char *buf = NULL; /* failed is special. We use bitwise ops, but it is essentially bool. */ int i = 0, ret = 0, failed = 0; + int bufsize; + static int oldbufsize = 0;
if (writecnt > 65536 || readcnt > 65536) return SPI_INVALID_LENGTH;
- buf = realloc(buf, writecnt + readcnt + 100); - if (!buf) { - fprintf(stderr, "Out of memory!\n"); - exit(1); // -1 + /* buf is not used for the response from the chip. */ + bufsize = max(writecnt + 9, 260 + 9); + /* Never shrink. realloc() calls are expensive. */ + if (bufsize > oldbufsize) { + buf = realloc(buf, bufsize); + if (!buf) { + fprintf(stderr, "Out of memory!\n"); + exit(1); + } + oldbufsize = bufsize; }
/*