#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>

int main(int argc, char **argv)
{
  int fd;
  off_t len;
  char buf[8192];
  int i;
  int size;
  struct timeval begin_t;

  if (argc != 3)
  {
    printf("Usage: writetest <filename> <size in MB>\n");
    exit(1);
  }

  fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, S_IWUSR | S_IRUSR);
  if (fd == -1)
  {
    perror(NULL);
    exit(1);
  }
  size = atoi(argv[2]) * 1024 * 1024;

  for(i=0; i < size;)
    i += write(fd, buf, sizeof(buf));

  len = i;

  fsync(fd);

  gettimeofday(&begin_t, NULL);
  for(i = 0; i < 10000000; i++)
  {
    lseek(fd, ((random() % (len / sizeof(buf)))) * sizeof(buf), SEEK_SET);
    write(fd, buf, sizeof(buf));
    if(i % 40000 == 0)
    {
      struct timeval t;
      long msecs;

      gettimeofday(&t, NULL);
      msecs = (t.tv_sec - begin_t.tv_sec) * 1000 +(t.tv_usec - begin_t.tv_usec) / 1000;
      printf("%d blocks written, time=%ld ms\n", i, msecs);
      begin_t = t;
    }
  }
}
