#!/usr/bin/perl

use strict;
use warnings;

use Time::HiRes qw(gettimeofday);
use Sys::Guestfs;

my $g = Sys::Guestfs->new();
$g->add_drive('test.img');
$g->launch();
$g->mkfs('ext2', '/dev/sda');
$g->mount_options('', '/dev/sda', '/');

my $buf = "";
for (my $i = 0; $i < 256; $i++) {
    substr($buf, $i, 1, chr($i));
}

for (my $i = 0; $i < 13; $i++) {
    $buf .= $buf;
}

my $rounds = 2**7;

print "Writing ".length($buf) * $rounds." bytes in ".length($buf).
      " byte chunks\n";

$| = 1;

my @start;
sub test_start
{
    $g->touch('/test');
    $g->truncate_size('/test', 0);

    @start = gettimeofday();
}

sub test_finish
{
    my @end = gettimeofday();

    my $elapsed = $end[0] * 1000000 + $end[1] - $start[0] * 1000000 - $start[1];
    $elapsed /= 1000000;

    print " $elapsed seconds\n";
}

sub test_pwrite
{
    test_start();

    print "Testing pwrite...";

    my $out = 0;
    for (my $i = 0; $i < $rounds; $i++) {
        my $written = $g->pwrite('/test', $buf, $out);
        $out += $written;
    }

    $g->sync();

    test_finish();
}

test_pwrite();
