added -B options
[tridge/junkcode.git] / writefiles.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <fcntl.h>
5 #include <errno.h>
6 #include <sys/time.h>
7
8
9 static struct timeval tp1,tp2;
10 static size_t block_size = 64 * 1024;
11
12 static void start_timer()
13 {
14         gettimeofday(&tp1,NULL);
15 }
16
17 static double end_timer()
18 {
19         gettimeofday(&tp2,NULL);
20         return((tp2.tv_sec - tp1.tv_sec) + 
21                (tp2.tv_usec - tp1.tv_usec)*1.0e-6);
22 }
23
24
25 static void write_file(char *fname)
26 {
27         int fd;
28         static double total, thisrun;
29         int n;
30         char *buf;
31
32         buf = malloc(block_size);
33
34         if (!buf) {
35                 printf("Malloc of %d failed\n", block_size);
36                 exit(1);
37         }
38
39         fd = open(fname, O_WRONLY|O_SYNC);
40         if (fd == -1) {
41                 perror(fname);
42                 free(buf);
43                 return;
44         }
45
46         while ((n = write(fd, buf, block_size)) > 0) {
47                 total += n;
48                 thisrun += n;
49                 if (end_timer() >= 1.0) {
50                         printf("%d MB    %g MB/sec\n", 
51                                (int)(total/1.0e6),
52                                (thisrun*1.0e-6)/end_timer());
53                         start_timer();
54                         thisrun = 0;
55                 }
56         }
57
58         free(buf);
59         close(fd);
60 }
61
62
63 static void usage(void)
64 {
65         printf("
66 writefiles - writes to a list of files, showing throughput
67
68 Usage: writefiles [options] <files>
69
70 Options:
71     -B size        set the block size in bytes
72
73 WARNING: writefiles is a destructive test!
74
75 ");
76 }
77
78
79 int main(int argc, char *argv[])
80 {
81         int i;
82         extern char *optarg;
83         extern int optind;
84         int c;
85
86         while ((c = getopt(argc, argv, "B:h")) != -1) {
87                 switch (c) {
88                 case 'B':
89                         block_size = strtol(optarg, NULL, 0);
90                         break;
91                 case 'h':
92                 default:
93                         usage();
94                         exit(1);
95                 }
96         }
97
98         argc -= optind;
99         argv += optind;
100
101         if (argc == 0) {
102                 usage();
103                 exit(1);
104         }
105
106
107         start_timer();
108
109         while (1) {
110                 for (i=0; i<argc; i++) {
111                         write_file(argv[i]);
112                 }
113         }
114
115         return 0;
116 }
117