summaryrefslogtreecommitdiff
path: root/disk_perf.c
blob: 81c40955eb440327f7f429fa1791b9d708366455 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <assert.h>
#include <sys/time.h>

static uint64_t gettimestamp() {
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return tv.tv_sec * 1000000ULL + tv.tv_usec;
}

static void writeall(int fd, const void *buf, size_t count) {
  size_t cursor = 0;
  while (cursor < count) {
    ssize_t written = write(fd, buf + cursor, count - cursor);
    if (written < 0) {
      perror("write");
      exit(1);
    }
    assert(written > 0);
    cursor += written;
  }
}

int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "Usage: %s <temp file to use>\n", argv[0]);
    fprintf(stderr,
        "This will write some data to a file as many times per second as\n"
        "possible, calling fsync() after each write to make sure it is\n"
        "persisted. This gives an upper bound on the number of ACID transactions\n"
        "a single-threaded database can achieve on a disk.\n"
		"The amount of data in one write is currently 18 bytes.\n"
    );
    return 1;
  }

  int fd = open(argv[1], O_WRONLY | O_CREAT, 0644);
  if (fd < 0) {
    perror("open");
    return 1;
  }

  uint64_t start_stamp = gettimestamp();
  size_t num_writes = 0;
  for (size_t i = 0; ; i++) {
    const char *str = "abcdefgh=01234567\n";
    writeall(fd, str, strlen(str));
    fsync(fd);
    num_writes++;

    if (i % 100 == 0) {
      uint64_t now = gettimestamp();
      double secs = (double)(now - start_stamp) / 1000000;
      if (secs >= 4.0) {
        printf("Speed: %zu writes in %lf seconds = %lf w/s\n",
               num_writes, secs, num_writes / secs);

        start_stamp = now;
        num_writes = 0;
      }
    }
  }
}