From 055e2115de90893b01c8214cee805ae5fd669a7c Mon Sep 17 00:00:00 2001 From: Michael Sevakis Date: Tue, 28 Nov 2017 08:06:30 -0500 Subject: [PATCH] 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 --- firmware/common/fdprintf.c | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/firmware/common/fdprintf.c b/firmware/common/fdprintf.c index 21d0a72e58..3dabbf3462 100644 --- a/firmware/common/fdprintf.c +++ b/firmware/common/fdprintf.c @@ -19,24 +19,37 @@ * ****************************************************************************/ #include +#include "system.h" #include "file.h" #include "vuprintf.h" +#define FPR_WRBUF_CKSZ 32 /* write buffer chunk size */ + struct for_fprintf { int fd; /* where to store it */ 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) { struct for_fprintf *fpr = (struct for_fprintf *)pr; - /* TODO: add a small buffer to reduce write() calls */ - if (write(fpr->fd, &(char){ letter }, 1) > 0) { - return --fpr->rem; + if (fpr->idx >= FPR_WRBUF_CKSZ && fpr_buffer_flush(fpr)) { + return -1; /* don't count this one */ } - return -1; + fpr->wrbuf[fpr->idx++] = letter; + return --fpr->rem; } int fdprintf(int fd, const char *fmt, ...) @@ -47,10 +60,16 @@ int fdprintf(int fd, const char *fmt, ...) fpr.fd = fd; fpr.rem = INT_MAX; + fpr.idx = 0; va_start(ap, fmt); bytes = vuprintf(fprfunc, &fpr, fmt, 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; }