Created
October 2, 2023 13:56
-
-
Save matvore/301f2cf8ba0fc7699ddf26e55274a6bc to your computer and use it in GitHub Desktop.
putc vs buffering benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
static FILE *fin, *fout; | |
static void byteperbyte(void) | |
{ | |
int c; | |
while (EOF != (c=getc(fin))) putc(c, fout); | |
} | |
static void selfbuffer(void) | |
{ | |
#define BS 256 | |
char buf1[BS], buf2[BS]; | |
unsigned sz, i; | |
while (sz=fread(buf1, 1, BS, fin)) { | |
for (i = 0; i < sz; i++) buf2[i] = buf1[i]; | |
fwrite(buf2, sz, 1, fout); | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
char method; | |
const char *dest; | |
if (argc != 3 || !(strchr("1b", method=*argv[1]))) { | |
fprintf(stderr, "usage: %s [1|b] DEST\n", *argv); | |
exit(1); | |
} | |
dest = argv[2]; | |
fin = fopen("/usr/share/dict/words", "r"); | |
if (!fin) { perror("fopen source"); abort(); } | |
fout = fopen(dest, "w"); | |
if (!fout) { perror("fopen dest"); abort(); } | |
switch (method) { | |
case '1': byteperbyte(); break; | |
case 'b': selfbuffer(); break; | |
default: abort(); | |
} | |
fflush(fout); | |
if (ferror(fin)) fprintf(stderr, "input error\n"); | |
if (ferror(fout)) fprintf(stderr, "output error\n"); | |
fclose(fin); | |
fclose(fout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment