Add a small 32-byte write buffer to fdprintf.

Avoids a call to write() for every output character. It doesn't
need to be very large to have a great effect on speed and realize
most of the potential.

Change-Id: I11820c1968ed7b20aa00e106a022c1b864b03d21
This commit is contained in:
Michael Sevakis 2017-11-28 08:06:30 -05:00
parent d728b9775b
commit 055e2115de

View file

@ -19,24 +19,37 @@
* *
****************************************************************************/ ****************************************************************************/
#include <limits.h> #include <limits.h>
#include "system.h"
#include "file.h" #include "file.h"
#include "vuprintf.h" #include "vuprintf.h"
#define FPR_WRBUF_CKSZ 32 /* write buffer chunk size */
struct for_fprintf { struct for_fprintf {
int fd; /* where to store it */ int fd; /* where to store it */
int rem; /* amount remaining */ int rem; /* amount remaining */
int idx; /* index of next buffer write */
unsigned char wrbuf[FPR_WRBUF_CKSZ]; /* write buffer */
}; };
static int fpr_buffer_flush(struct for_fprintf *fpr)
{
/* set idx to actual but negative unflushed count to signal error */
ssize_t done = write(fpr->fd, fpr->wrbuf, fpr->idx);
fpr->idx = MAX(done, 0) - fpr->idx;
return fpr->idx;
}
static int fprfunc(void *pr, int letter) static int fprfunc(void *pr, int letter)
{ {
struct for_fprintf *fpr = (struct for_fprintf *)pr; struct for_fprintf *fpr = (struct for_fprintf *)pr;
/* TODO: add a small buffer to reduce write() calls */ if (fpr->idx >= FPR_WRBUF_CKSZ && fpr_buffer_flush(fpr)) {
if (write(fpr->fd, &(char){ letter }, 1) > 0) { return -1; /* don't count this one */
return --fpr->rem;
} }
return -1; fpr->wrbuf[fpr->idx++] = letter;
return --fpr->rem;
} }
int fdprintf(int fd, const char *fmt, ...) int fdprintf(int fd, const char *fmt, ...)
@ -47,10 +60,16 @@ int fdprintf(int fd, const char *fmt, ...)
fpr.fd = fd; fpr.fd = fd;
fpr.rem = INT_MAX; fpr.rem = INT_MAX;
fpr.idx = 0;
va_start(ap, fmt); va_start(ap, fmt);
bytes = vuprintf(fprfunc, &fpr, fmt, ap); bytes = vuprintf(fprfunc, &fpr, fmt, ap);
va_end(ap); va_end(ap);
/* flush any tail bytes */
if (fpr.idx < 0 || fpr_buffer_flush(&fpr)) {
bytes += fpr.idx; /* adjust for unflushed bytes */
}
return bytes; return bytes;
} }