From e6c6534a3d68a7cec461f115f14d8a9a2d681a90 Mon Sep 17 00:00:00 2001 From: Mattia Cabrini Date: Tue, 9 Sep 2025 18:45:58 +0200 Subject: [PATCH] +Buffered reading (6.3x times faster) --- cmc-find.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/cmc-find.c b/cmc-find.c index c06cd26..5fa4093 100644 --- a/cmc-find.c +++ b/cmc-find.c @@ -11,6 +11,10 @@ #define MAX_LEN 64 #endif +#ifndef BUF_LEN +#define BUF_LEN (64*1024) +#endif + typedef struct cs_t { char buf[MAX_LEN]; @@ -19,11 +23,24 @@ typedef struct cs_t { size_t start; /* index of firs char */ } *cs; +typedef struct buf_t { + char buf[BUF_LEN]; + + FILE *fp; + size_t cap /* max string size; <= MAX_LEN */ ; + size_t cur; +} *buf; + static void cs_init(cs S, size_t cap); static void cs_add(cs S, char ch); static int cs_cmp(cs S, char *ch); static void cs_print(cs S); +static void buf_init(buf B, FILE *); +static void buf_read(buf B); +static char buf_next_ch(buf B); +static int buf_eof(buf B); + int main(int argc, char **argv) { int ch = 0; @@ -31,7 +48,8 @@ int main(int argc, char **argv) time_t now; char str[MAX_LEN]; - struct cs_t matcher; + struct cs_t S; + struct buf_t B; if (argc < 2) { printf("Usage: %s \n", argv[0]); @@ -41,15 +59,20 @@ int main(int argc, char **argv) printf("Check against %s\n", str); now = time(0); - cs_init(&matcher, strlen(str)); + buf_init(&B, stdin); + cs_init(&S, strlen(str)); + + for (n = 1;; ++n) { + ch = buf_next_ch(&B); + if (!ch && buf_eof(&B)) + break; - for (n = 1; (ch = fgetc(stdin)) != EOF; ++n) { - cs_add(&matcher, ch); + cs_add(&S, ch); - if (matcher.len == matcher.cap) { - if (cs_cmp(&matcher, str)) { - printf("Found at %llu\t%lu\n", n - matcher.cap, time(0) - now); - /* cs_print(&matcher); printf("\n"); */ + if (S.len == S.cap) { + if (cs_cmp(&S, str)) { + printf("Found at %llu\t%lu\n", n - S.cap, time(0) - now); + /* cs_print(&S); printf("\n"); */ } } } @@ -132,3 +155,31 @@ static void cs_print(cs S) ++count; } } + +static void buf_init(buf B, FILE * fp) +{ + B->cap = 0; + B->cur = 0; + B->fp = fp; +} + +static void buf_read(buf B) +{ + B->cap = fread(B->buf, 1, sizeof(B->buf), B->fp); + B->cur = 0; +} + +static char buf_next_ch(buf B) +{ + if (B->cur >= B->cap) { + buf_read(B); + if (B->cap == 0) + return '\0'; + } + return B->buf[B->cur++]; +} + +static int buf_eof(buf B) +{ + return feof(B->fp) && B->cur >= B->cap; +} -- 2.43.0