#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <unistd.h>
#include <string.h>

static char buf[40960];
static char name[32];
static char *prog_name;

extern int errno;

#define NDIR 100


static char timebuf[512];

time_t ds;
time_t du;
struct timeval s, f;

void start()
{
    gettimeofday(&s, NULL);
}


void stop()
{
    gettimeofday(&f, NULL);
    ds = f.tv_sec - s.tv_sec;
    du = f.tv_usec - s.tv_usec;
    if (du < 0) {
      ds -= 1;
      du += 1000000;
    }
    sprintf(timebuf, "%d.%06d", (unsigned int)ds, (unsigned int)du);
}


void read_test(int n, int size)
{
    int i=0;
    int r;
    int fd;
    int j;

    start();
    for (i = 0, j = 0; i < n; i ++) {

	sprintf(name, "d%d/g%d", j, i);

	if((fd = open(name, O_RDONLY)) < 0) {
	    printf("%s: open %d failed %d %d\n", prog_name, i, fd, errno);
	    exit(1);
	}

	if ((r = read(fd, buf, size)) < 0) {
	    printf("%s: read failed %d %d\n", prog_name, r, errno);
	    exit(1);
	}

	if ((r = close(fd)) < 0) {
	    printf("%s: close failed %d %d\n", prog_name, r, errno);
	}

	if ((i+1) % 100 == 0) j++;
    }

    stop();
    printf("%s: read took %s sec\n", prog_name, timebuf);
}


int main(int argc, char *argv[])
{
    int n;
    int size;

    prog_name = argv[0];

    if (argc != 3) {
	printf("%s: %s num size\n", prog_name, prog_name);
	exit(1);
    }

    n = atoi(argv[1]);
    size = atoi(argv[2]);

    printf("%s %d %d\n", prog_name, n, size);
    
    read_test(n, size);
    return 0;
}
