#define _GNU_SOURCE
#include <fcntl.h>

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


int main(int argc, char**argv) {

  struct timeval t1, t2;
  gettimeofday(&t1, NULL);
  if(argc < 2) {
    fprintf(stderr, "Usage: %s input_file output_file\n", argv[0]);
    return EXIT_FAILURE;
  }
  int f_in= open(argv[1], O_RDONLY);
  int f_out= open(argv[2], O_WRONLY|O_CREAT|O_TRUNC|O_SYNC|O_DIRECT, S_IRUSR);
  assert(f_in >= 0);
  assert(f_out >= 0);

  int n_bytes=0;
  char c;
  while(read(f_in, &c, sizeof(char))) {
    write(f_out, &c, sizeof(char));
    n_bytes++;
  }
  close(f_in);
  close(f_out);

  gettimeofday(&t2, NULL);
  double duration = (t2.tv_sec - t1.tv_sec)*1e6 + (t2.tv_usec - t1.tv_usec);
  double rate=n_bytes/duration;
  printf("%d bytes copied in %lf usec -> %lf MB/s\n", n_bytes, duration, rate);

  int n_functions=2*n_bytes;
  double cost_per_function=duration/n_functions;
  printf("-> %lf usec/ function call\n", cost_per_function);
  return EXIT_SUCCESS;
}
