Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* C best of 10 reads (7200 rpm laptop drive):
- * read/stored 25481 lines in 0.003850 sec.
- * total heap usage: 25,494 allocs, 25,494 frees, 733,979 bytes allocated
- * (reading, e.g. /usr/share/dict/words)
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- enum { MAXP = 8, MAXC = 512 };
- /** reallocate block of 'psz' objects to twice 'nelem'.
- * 'nelem' is updated to reflect the new allocation size.
- * exits on allocation failure.
- */
- void *xrealloc2 (void *ptr, size_t psz, size_t *nelem)
- {
- void *memptr = realloc ((char *)ptr, *nelem * 2 * psz);
- if (!memptr) {
- fprintf (stderr, "realloc() error: virtual memory exhausted.\n");
- exit (EXIT_FAILURE);
- }
- /* zero new memory (optional) */
- memset ((char *)memptr + *nelem * psz, 0, *nelem * psz);
- *nelem *= 2;
- return memptr;
- }
- /** return the number of seconds (nanosecond resolution)
- * using clock_gettime/CLOCK_REALTIME
- */
- double clkrtv (void)
- {
- struct timespec ts;
- double sec;
- clock_gettime (CLOCK_REALTIME, &ts);
- sec = ts.tv_nsec;
- sec /= 1e9;
- sec += ts.tv_sec;
- return sec;
- }
- int main (int argc, char **argv) {
- size_t n = 0,
- size = MAXP; /* initialize 'size' to MAXP */
- double t1, t2;
- char tmp[MAXC] = "", /* tmp buffer for read of MAXC chars */
- **buf = NULL;
- FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
- if (!fp) { /* validate file open for reading */
- fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
- return 1;
- }
- /* allocate/validate 'size' ptrs to char */
- if (!(buf = calloc (size, sizeof *buf))) {
- fprintf (stderr, "error; virtual memory exhausted.\n");
- return 1;
- }
- t1 = clkrtv();
- while (fgets (tmp, MAXC, fp)) { /* read each line */
- size_t l = strlen (tmp); /* get length */
- if (l && tmp[l - 1] == '\n') /* trim '\n' */
- tmp[--l] = 0;
- if (!(buf[n] = malloc (l + 1))) /* allocate for line */
- goto memfull;
- strcpy (buf[n++], tmp); /* copy to buf[n] */
- if (n == size) /* realloc as required */
- buf = xrealloc2 (buf, sizeof *buf, &size);
- }
- memfull:;
- t2 = clkrtv();
- printf ("read/stored %zu lines in %.6f sec.\n", n, t2-t1);
- if (fp != stdin) fclose (fp); /* close file if not stdin */
- for (size_t i = 0; i < n; i++) /* free allocated memory */
- free (buf[i]);
- free (buf);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement