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

my $dbh = DBI->connect("dbi:mysql:database=test") or die "Can't connect to DB";
my @tables = qw(t_0 t_1 t_2 t_3 t_5 t_all);

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

	my $time;
	$time->{'prepare'} = [gettimeofday()];
	my $result = $sth->execute($test);
	$time->{'execute'} = [gettimeofday()];
	my $i = 0;
	while (my $ref = $sth->fetchrow_hashref) {
		$i++;
		my $id = $ref->{'ID'};
		my $name = $ref->{'name'};
		print "Got: $id, $name\n";
	}
	$time->{'done'} = [gettimeofday()];

	my $t;
	$t->{'execute'}= tv_interval($time->{'prepare'},  $time->{'execute'});
	$t->{'fetch'}= $i>0?(tv_interval($time->{'execute'}, $time->{'done'}) / $i):0;
	return $t;
}

sub do_timings {
	my $timings;
	my $sth;
	foreach (@tables) {
		$sth->{$_} = $dbh->prepare("SELECT * from $_ where name = ?");
	}
	for (my $loop=1; $loop < 100; $loop++) {
		my $test;
		for (my $i = 0; $i<10; $i++){
			$test.= int rand(25);
		}
		#print "Looking for $test\n";
		foreach (@tables) {
			push @{$timings->{$_}}, do_query($sth->{$_}, $test);
		}
	}
	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:\t";
		foreach my $op (keys %{$averages->{$type}}) {
			$averages->{$type}->{$op}/=$num_tests;
			printf "%s = %0.6f\t", $op, $averages->{$type}->{$op};
		}
		print "\n";
	}
}

do_timings();
