#!/usr/bin/perl
use DBI;
use Benchmark;

$opt_loop_count=100000;		# number of loops(rows)

$db_host="localhost";
$db_socket="/tmp/mysql.sock";
$db_name="test";
$db_engine="InnoDB";
$db_stat=1;                     # set to 1 to get handler stats
                                # before and after update_with_key_prefix operation

$dbh = DBI->connect("dbi:mysql:$db_name;host=$db_host;mysql_socket=$db_socket","root","") or die $DBI::errstr;

####
#### Create needed table
####

print "Creating table bench1\n";
$dbh->do("drop table if exists bench1 ") or die $DBI::errstr;
$dbh->do("create table bench1 (id int NOT NULL, 
                               id2 int NOT NULL,
                               id3 int NOT NULL,
                               dummy1 char(30),
                               primary key (id,id2),
                               index ix_id3 (id3)) engine=$db_engine") or die $DBI::errstr;

$query="insert into bench1 (id,id2,id3,dummy1) values ";

print "Inserting $opt_loop_count rows in order\n";

$loop_time=new Benchmark;
for ($i=0 ; $i < $opt_loop_count ; $i++)
{
  $sth = $dbh->do($query . "($i,$i,$i,'ABCDEFGHIJ')") or die $DBI::errstr;
}
  
$end_time=new Benchmark;
print "Time for insert_in_order (" . ($opt_loop_count) . "): " .
  timestr(timediff($end_time, $loop_time),"all") . "\n\n";

print "Testing update with key\n";
$loop_time=new Benchmark;;
for ($i=0 ; $i < $opt_loop_count ; $i++)
{
  $sth = $dbh->do("update bench1 set dummy1='updated' where id=$i and id2=$i") or die $DBI::errstr;
}

$end_time=new Benchmark;;
print "Time for update_with_key (" . ($opt_loop_count) . "):  " .
  timestr(timediff($end_time, $loop_time),"all") . "\n";

if ($db_stat)
{
  $sth=$dbh->prepare("show status like 'handler%'");
  $sth->execute();
  while ((@arr=$sth->fetchrow_array))
  {
    print join(",",@arr),"\n";
  }
  $sth->finish;
}

print "Testing update with key prefix\n";
$loop_time=new Benchmark;
for ($i=1 ; $i < $opt_loop_count ; $i++)
{
  $sth = $dbh->do("update bench1 set dummy1='updated' where id=$i") or die $DBI::errstr;
}

$end_time=new Benchmark;
print "Time for update_with_key_prefix (" . ($opt_loop_count) . "):  " .
  timestr(timediff($end_time, $loop_time),"all") . "\n";

if ($db_stat)
{
  $sth=$dbh->prepare("show status like 'handler%'");
  $sth->execute();
  while ((@arr=$sth->fetchrow_array))
  {
    print join(",",@arr),"\n";
  }
  $sth->finish;
}

$dbh->disconnect();
