Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // читаем построчно файлы из арг. ком. стр. 2-мя разными способами malloc/realloc
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #include <sys/time.h>
- #define LIMIT 100000000
- double getusec()
- {
- struct timeval tm;
- gettimeofday(&tm, 0);
- return tm.tv_sec * 1.0e6 + tm.tv_usec;
- }
- char *
- getaline (FILE *in)
- {
- // ./a.out /usr/include/*.h
- #if QUICK // read 1403382 bytes in 39654 lines in 145 files (131.525 msec) maxcap: 3415 (2796)
- static int cap = 0;
- static char *str = 0;
- #else // read 1403382 bytes in 39654 lines in 145 files (152.583 msec) maxcap: 3415 (2796)
- int cap = 0;
- char *str = 0;
- #endif // сам удивился, что не влияет
- int c, n = 0, incr = 10;
- if (feof(in))
- return 0;
- while ((c = fgetc(in)) != EOF) {
- if (n + 2 > cap) {
- str = realloc(str, (cap += incr));
- #if QUICK
- incr <<= 1;
- #endif
- }
- str[n++] = c;
- if (c == '\n')
- break;
- }
- if (n) {
- str[n] = 0;
- #if QUICK
- char *t = malloc(n + 1);
- memcpy(t, str, n + 1);
- return t;
- #else
- return realloc(str, n + 1);
- #endif
- }
- return 0;
- }
- int
- read_filines (FILE *in, int *lines, int *pcap, int *pn)
- {
- int i, size = 0, acap = 0, n = 0, incr = 300;
- char *str, **arr = 0;
- while (str = getaline(in)) {
- size += strlen(str);
- if (n == acap) {
- arr = realloc(arr, (acap += incr) * sizeof(*arr));
- if ((incr = acap / 2) > 10000)
- incr = 16000;
- }
- arr[n++] = str;
- }
- (*lines) += n;
- for (i = 0; i < n; i++)
- free(arr[i]);
- free(arr);
- *pn = n;
- *pcap = acap;
- return size;
- }
- int
- main (int ac, char *av[])
- {
- #if QUICK
- puts("Quick test");
- #else
- puts("Slow test");
- #endif
- double t1 = getusec();
- FILE *in;
- int i, n = 0, tot = 0, size = 0, cap, maxcap = 0, na, maxna = 0;
- for (i = 1; i < ac; i++) {
- if (in = fopen(av[i], "r")) {
- n++;
- size += read_filines(in, &tot, &cap, &na);
- if (cap > maxcap)
- maxcap = cap;
- if (na > maxna)
- maxna = na;
- if (size > LIMIT)
- break;
- fclose(in);
- } else
- perror(av[i]);
- }
- printf ("read %d bytes in %d lines in %d files (%.3f msec) maxcap: %d (%d)\n",
- size, tot, n, (getusec() - t1) / 1000, maxcap, maxna);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement