#!/usr/bin/perl -w
use strict;
use DBI;
use Time::HiRes qw(gettimeofday tv_interval);

my @tables = qw(t_0 t_1 t_2 t_3 t_5 t_all);

my $dbh = DBI->connect("dbi:mysql:database=test") or die "Can't connect to DB";


sub do_query {
	my $sth= shift;
	my $test = shift;

	my $time;
	$time->{'prepare'} = [gettimeofday()];
	my $result = $sth->execute;
	$time->{'execute'} = [gettimeofday()];

	my $t;
	$t->{'execute'}= tv_interval($time->{'prepare'},  $time->{'execute'});
	return $t;
}

sub check_contents() {
	my $sql = "select count(1) as Count from ";
	my $counts;
	foreach (sort @tables) {
		my $sth = $dbh->prepare($sql . $_);
		$sth->execute;
		my $ref = $sth->fetchrow_hashref;
		printf "%s: %d\t", $_, $ref->{'Count'};
	}
	print "\n";
}

sub do_inserts {
	my $timings;
	print "Starting first insert\n";
	my $sth;
	foreach (@tables) {
		$sth->{$_} = $dbh->prepare("insert into $_ set name = '?'");
	}

	for (my $loop=0; $loop < 10000; $loop++) {
		my $test;
		for (my $i = 0; $i<10; $i++){
			$test.= int rand(25);
		}
		foreach (@tables) {
			push @{$timings->{$_}}, do_query($sth->{$_}, $test);
		}
	}
	print "Timings:\n";
	my $averages;
	foreach my $type (sort keys %{$timings}) {
		my $num_tests = 0;
		foreach my $test (@{$timings->{$type}}) {
			$num_tests++;
			foreach my $op (keys %{$test}) {
				$averages->{$type}->{$op}+=$test->{$op};
			}
		}
		print "$type: ";
		foreach my $op (sort keys %{$averages->{$type}}) {
			$averages->{$type}->{$op}/=$num_tests;
			printf "%s = %.8f ms\t", $op, $averages->{$type}->{$op} * 1000;
		}
		print "\n";
	}
}

#do_inserts();
check_contents();
