All pastes #82960 Raw Edit

stat(2) vs readdir(3

public c v1 · immutable
·published 2006-07-09 04:40 UTC
rendered paste body
/* Compare the speed of stat vs readdir to get a mapping of files which exist. */#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <dirent.h>#include <sys/time.h>int main(int argc, char **argv){        int i, mapsize;        struct timeval start1, end1, start2, end2;        struct stat mystat;        char filename[256];        unsigned char *mymap;        DIR *mydir;        struct dirent *mydirent;        int mydirint;        srandom(getpid());        if (argc == 2) {                sscanf(argv[1], "%d", &mapsize);        } else {                mapsize = 1000;        }        mymap = calloc(1, mapsize);        gettimeofday(&start1, NULL);        for (i = 0; i < mapsize; i++) {                snprintf(filename, sizeof(filename), "/home/tilghman/Asterisk/stattest/msg%04d.txt", i);                if (stat(filename, &mystat)) {                        /* file doesn't exist */                        break;                }        }        gettimeofday(&end1, NULL);        printf("Search time for stat for %d entries was %.05f seconds (found at position %d)\n", mapsize, end1.tv_sec * 1.0 - start1.tv_sec * 1.0 + end1.tv_usec / 1000000.0 - start1.tv_usec / 1000000.0, i);        gettimeofday(&start2, NULL);        mydir = opendir("/home/tilghman/Asterisk/stattest");        while ((mydirent = readdir(mydir))) {                if (sscanf(mydirent->d_name, "msg%d", &mydirint) == 1 && mydirint < mapsize) {                        /* printf("Found %s at position %d\n", mydirent->d_name, mydirint); */                        mymap[mydirint] = 1;                }        }        closedir(mydir);        for (i = 0; i < mapsize; i++) {                if (mymap[i] == 0) {                        break;                }        }        gettimeofday(&end2, NULL);        printf("Search time for opendir for %d entries was %.05f seconds (found at position %d)\n", mapsize, end2.tv_sec * 1.0 - start2.tv_sec * 1.0 + end2.tv_usec / 1000000.0 - start2.tv_usec / 1000000.0, i);        exit(0);}