1/*
2 * writetest --
3 *
4 * $Id: writetest.cs,v 10.8 2005/09/13 18:15:36 bostic Exp $
5 */
6#include <sys/types.h>
7#include <sys/time.h>
8
9#include <errno.h>
10#include <fcntl.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <unistd.h>
15
16void usage(void);
17
18int
19main(argc, argv)
20	int argc;
21	char *argv[];
22{
23	struct timeval start_time, end_time;
24	double usecs;
25	long val;
26	int bytes, ch, cnt, fd, ops;
27	char *fname, buf[100 * 1024];
28
29	bytes = 256;
30	fname = "testfile";
31	ops = 1000;
32	while ((ch = getopt(argc, argv, "b:f:o:")) != EOF)
33		switch (ch) {
34		case 'b':
35			if ((bytes = atoi(optarg)) > sizeof(buf)) {
36				fprintf(stderr,
37				    "max -b option %d\n", sizeof(buf));
38				exit (1);
39			}
40			break;
41		case 'f':
42			fname = optarg;
43			break;
44		case 'o':
45			if ((ops = atoi(optarg)) <= 0) {
46				fprintf(stderr, "illegal -o option value\n");
47				exit (1);
48			}
49			break;
50		case '?':
51		default:
52			usage();
53		}
54	argc -= optind;
55	argv += optind;
56
57	(void)unlink(fname);
58	if ((fd = open(fname, O_RDWR | O_CREAT, 0666)) == -1) {
59		perror(fname);
60		exit (1);
61	}
62
63	memset(buf, 0, bytes);
64
65	printf("Running: %d ops\n", ops);
66
67	(void)gettimeofday(&start_time, NULL);
68	for (cnt = 0; cnt < ops; ++cnt) {
69		if (write(fd, buf, bytes) != bytes) {
70			fprintf(stderr, "write: %s\n", strerror(errno));
71			exit (1);
72		}
73		if (lseek(fd, (off_t)0, SEEK_SET) == -1) {
74			fprintf(stderr, "lseek: %s\n", strerror(errno));
75			exit (1);
76		}
77		if (fsync(fd) != 0) {
78			fprintf(stderr, "fsync: %s\n", strerror(errno));
79			exit (1);
80		}
81	}
82	(void)gettimeofday(&end_time, NULL);
83
84	/*
85	 * Guarantee end_time fields are greater than or equal to start_time
86	 * fields.
87	 */
88	if (end_time.tv_sec > start_time.tv_sec) {
89		--end_time.tv_sec;
90		end_time.tv_usec += 1000000;
91	}
92
93	/* Display elapsed time. */
94	val = end_time.tv_sec - start_time.tv_sec;
95	printf("Elapsed time: %ld:", val / (60 * 60));
96	val %= 60 * 60;
97	printf("%ld:", val / 60);
98	val %= 60;
99	printf("%ld.%ld\n", val, end_time.tv_usec - start_time.tv_usec);
100
101	/* Display operations per second. */
102	usecs =
103	    (end_time.tv_sec - start_time.tv_sec) * 1000000 +
104	    (end_time.tv_usec - start_time.tv_usec);
105	printf("%d operations: %7.2f operations per second\n",
106	    ops, (ops / usecs) * 1000000);
107
108	(void)unlink(fname);
109	exit (0);
110}
111
112void
113usage()
114{
115	(void)fprintf(stderr,
116	    "usage: testfile [-b bytes] [-f file] [-o ops]\n");
117	exit(1);
118}
119