#!/usr/bin/perl -w

use Sys::Mmap;
#use Benchmark ':hireswallclock';
#use Time::HiRes qw(gettimeofday tv_interval);
use strict;

my $mmapsize = 2000;
my $mmapfile = "/mnt/sata1/mmaptest.file";

my $bytes = $mmapsize * 1048576;
my ($fh, $mmap);

unless (-f $mmapfile and -s _ == $bytes) {
  print "Creating ${mmapsize}M file $mmapfile\n";
  system("/bin/dd", "if=/dev/zero", "of=$mmapfile", "bs=1048576", "count=$mmapsize");
  system("/bin/sync");
  print "Done, run again for mmap test\n";
  exit;
}

print "${mmapsize}M file exists $mmapfile, mapping\n";

open($fh, "+<", $mmapfile)
    || die "Could not open map file: $!\n";
mmap($mmap, $bytes, PROT_READ|PROT_WRITE, MAP_SHARED, $fh);

print "Modifying random ranges in mmaped file\n";

foreach my $i (1..200000) {
  my $len = rand(10000);
  my $pos = int(rand($bytes - $len - 1));
  my $char = chr(ord('a') + rand(26));
  substr($mmap, $pos, $len) = $char x $len;

  $len = rand(10000);
  $pos = int(rand($bytes - $len - 1));
  my $read = substr($mmap, $pos, $len);

  unless ($i % 1000) {
    print "at $i\n";
  }
}

print "Unmapping\n";

munmap($mmap);
close($fh);

print "Done\n";

