#!/usr/bin/perl


#
# Performance test : time to read all symlinks in a directory for increasing
# number of symlinks.
#

use strict;
use warnings;
use Getopt::Long;

use FindBin;

# First do it using absolute pathnames
my $outfile = "results/SYM-ABS-NONEST.dat";
get_results($outfile, "no", 0);

# then with relative pathnames
$outfile = "results/SYM-REL-NONEST.dat";
get_results($outfile, "yes", 0);

# the subroutine for running the command with the given parameters.

sub get_results {

my($file, $relative, $depth) = @_;

my $optargs = "";
if ($relative eq "yes") {
  $optargs = $optargs."-r ";
}
if ($depth > 0) {
  $optargs = $optargs."-n $depth ";
}

# run the "symlinks" command with the different number of files and threads
# and get the times back in a file

my @threads = (1, 2, 5, 10, 20, 50);
my ($num_threads, $result);

open(OUTFILE, '>', "$file") or die "Can't open $file: $!\n";

print OUTFILE "num_threads, num_links, total_time (ms), thread_average (ms), link_average(ms)\n";

my($sec, $min, $hour, $day, $mon, $year, @rest) = localtime(time);
$year += 1900;
my $timestamp = "$year-$mon-$day-$hour:$min:$sec";
my $num_links = 1;
my $i = 0;
my $max_links = 10000;
my $increment = 1;
foreach $num_threads (@threads) {
      $num_links = 1;
      $i = 0;
      $increment = 1;	
      while ($num_links <= $max_links) {
	if ($i == 9) {
		$increment*=10;
		$i = 0;
	}	
	my $j = 0;
	my $total = 0;
	$result = 0;
	my $filename = "results/$num_threads-THREAD-$num_links-SYMLINKS.dat";
	`./symlinks -d /grid/dteam/caitriana/test2/symlinks/$timestamp-$num_threads -l $num_links -t $num_threads $optargs > $filename`;
	open(INFILE, "$filename") or die "Can't open $filename: $!\n";
	while (<INFILE>) {
		chomp;
		my @data = split /\s+/, $_;
                for($j=0; $j<$num_threads; $j++) {
			$result += $data[$j]/1000;
                }
		$total = $data[$j+1]/1000;
	}
	close INFILE;
	my $per_thread = $result/$num_threads;
	my $average = $per_thread/$num_links;
	print OUTFILE "$num_threads \t $num_links \t $total \t $per_thread \t $average\n";
	`nsrm -rf /grid/dteam/caitriana/test2/symlinks/$timestamp-$num_threads`;
	$i+=1;
	$num_links+=$increment;
	}
	`nsrm -rf /grid/dteam/caitriana/test2/symlinks/`;
}

close OUTFILE;

}
